I'm trying to upload a file to the server using WebClient. My code for posting the file is as follows:
public void UploadMultipart(byte[] file, string filename, string contentType, string url)
{
var webClient = new WebClient();
string boundary = "------------------------" + DateTime.Now.Ticks.ToString("x");
webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
var fileData = Encoding.UTF8.GetString(file);
var package = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}\r\n--{0}--\r\n", boundary, filename, contentType, fileData);
var nfile = webClient.Encoding.GetBytes(package);
byte[] resp = webClient.UploadData(url, "POST", nfile);
}
The line Encoding.UTF8.GetString(file)
always returns an empty string. I've checked the byte array and it's not empty. I also tried Encoding.UTF8.GetString(file, 0, file.Length)
but same result. I've read somewhere that this could be because of improper encoding. If that's the reason then how can I fix it? The file I'm trying to send is a video taken from a camera.
Any help is appreciated.