Question: How can we upload a file to a server?

Question

How can we upload a file to a server?

Answers 0
Added at 2016-12-25 18:12
Tags
Question

This is my api

[HttpPost]        
[Route("uploadfile")]

    public HttpResponseMessage PostFile(HttpRequest request)
    {
        HttpResponseMessage result = null;
        var httpRequest = request;//HttpContext.Current.Request;
        if (httpRequest.Files.Count > 0)
        {
            var docfiles = new List<string>();
            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var filePath = HttpContext.Current.Server.MapPath("Uploads/" + postedFile.FileName);
                postedFile.SaveAs(filePath);

                docfiles.Add(filePath);
            }
            result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
        }
        else
        {
            result = Request.CreateResponse(HttpStatusCode.BadRequest);
        }
        return result;
    }

This is my client code

  private async void button_Click(object sender, RoutedEventArgs e)
   {
   byte[] a = File.ReadAllBytes(@"C:\My folder\MyFile.txt");
        FileStream stream = File.Open(@"C:\My folder\MyFile.txt", FileMode.Open);

        Upload(@"http://localhost:56885/uploadfile", "MyFile", stream, a);

        MessageBox.Show("File uploaded Successfully");
   }

   private Stream Upload(string url, string param1, 
   Stream fileStream, byte[] fileBytes)        
   {
        HttpContent stringContent = new StringContent(param1);
        HttpContent fileStreamContent = new StreamContent(fileStream);
        HttpContent bytesContent = new ByteArrayContent(fileBytes);
        using (var client = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(stringContent, "param1", "param1");
            formData.Add(fileStreamContent, "file1", "file1");
            formData.Add(bytesContent, "file2", "file2");

            var response = client.PostAsync(url, formData).Result;

            if (!response.IsSuccessStatusCode)
            {
                return null;

            }

            MessageBox.Show("File uploaded Successfully");
            return response.Content.ReadAsStreamAsync().Result;
        }

    }

I was getting an error { "message": "The request entity's media type 'multipart/form-data' is not supported for this resource.", "exceptionMessage": "No MediaTypeFormatter is available to read an object of type 'HttpRequest' from content with media type 'multipart/form-data'.", "exceptionType": "System.Net.Http.UnsupportedMediaTypeException", "stackTrace": " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken) at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken) at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)" }

Answers
Source Show
◀ Wstecz