1

I wrote the following code for uploading files but when file is uploaded the type of it consider as "application/octet-stream", while they have different type such as image, video, audio, ... .

In addition, Although I wrote the request.AddHeader("Content-Type", "image/jpg");, the file.ContentType in the API is still "application/octet-stream"!

using RestSharp;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Text;

namespace WinFormsApp6
{
    public partial class Form1 : Form
    {
        private string filepaths = null;
        private string filetype = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "Select File";
            openFileDialog1.InitialDirectory = @"C:\";
            openFileDialog1.Filter = "All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 0;
            openFileDialog1.Multiselect = false;
            openFileDialog1.ShowDialog();
            if (openFileDialog1.FileName != "")
            {
                textBox1.Text = openFileDialog1.FileName;
                filepaths = openFileDialog1.FileName;
            }
            else
            {
                textBox1.Text = "Please select a file!";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (filepaths != null)
            {
                var client = new RestClient("http://localhost:7071/api/function1");
                var request = new RestRequest("http://localhost:7071/api/function1", Method.Post);
                request.AddFile("File", filepaths);
                request.AddHeader("ContentType", "image/jpeg");
                RestResponse response = client.Execute(request);
                Console.WriteLine(response.Content);
            }
        }
    }
}

Thanks,

amin
  • 93
  • 8

1 Answers1

1

You can set a correct MIME type yourself like this:

request.AddHeader("Content-Type", "application/json; charset=utf-8");

Here are some options to get the correct MIME type (content type) from the file name extension: Get MIME type from filename extension

  • Thanks, would you please elaborate more...Where I should use your line of code, and I should add the content type in "request.AddFile("File", filepaths);" as this is the code that send the file to destination? – amin Aug 26 '22 at 22:38
  • 1
    You can add it before client.Execute(). – Alexey Lerner Aug 27 '22 at 07:30
  • Although I wrote the...request.AddHeader("Content-Type", "image/jpg");...,the file.ContentType in the API is still "application/octet-stream"! – amin Aug 28 '22 at 18:58