1

I have a file upload module.its working well with postman with no content type.but in code always file count is getting as 0 in backend api.if anyone knows what i am doing wrong,please help me. thanks

here is my back end api`

    public async Task<HttpResponseMessage> PostUserImage()
    {
        Dictionary<string, object> dict = new Dictionary<string, object>();
        try
        {

            var httpRequest = HttpContext.Current.Request;

            foreach (string file in httpRequest.Files)
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);

                var postedFile = httpRequest.Files[file];
                if (postedFile != null && postedFile.ContentLength > 0)
                {

                    int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB  

                    IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
                    var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                    var extension = ext.ToLower();
                    if (!AllowedFileExtensions.Contains(extension))
                    {

                        var message = string.Format("Please Upload image of type .jpg,.gif,.png.");

                        dict.Add("error", message);
                        return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                    }
                    else if (postedFile.ContentLength > MaxContentLength)
                    {

                        var message = string.Format("Please Upload a file upto 1 mb.");

                        dict.Add("error", message);
                        return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                    }
                    else
                    {



                        var filePath = HttpContext.Current.Server.MapPath("~/Image/" + postedFile.FileName + extension);

                        postedFile.SaveAs(filePath);

                    }
                }

                var message1 = string.Format("Image Updated Successfully.");
                return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
            }
            var res = string.Format("Please Upload a image.");
            dict.Add("error", res);
            return Request.CreateResponse(HttpStatusCode.NotFound, dict);
        }
        catch (Exception ex)
        {
            var res = string.Format("some Message");
            dict.Add("error", res);
            return Request.CreateResponse(HttpStatusCode.NotFound, dict);
        }
    }`

this is what i am getting after posting through postmanwithout content type

and this is what i am getting in my developer consolecontent type is adding. my angular service foe uploading`

uploadimage:function(file,operation){
            var deferred = $q.defer();
            var httpReq = {
                method: operation,
                url: '/API/Customers/PostUserImage',
                data:file,
                transformRequest: angular.identity,

                headers: {
                    'content-type': 'multipart/form-data'
                },
                onSuccess: function (response, status) {
                    deferred.resolve(response);
                },
                onError: function (response) {
                    deferred.reject(response);
                }
            };
            httpService.call(httpReq);
            return deferred.promise;
        }`

this the controller code for appending to form data`

function readURL(input) {
        debugger;
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#imagePreview').css('background-image', 'url('+e.target.result +')');
                $('#imagePreview').hide();
                $('#imagePreview').fadeIn(650);
            }
            reader.readAsDataURL(input.files[0]);

            var filesformdata = new FormData();
            angular.forEach(input.files, function (value, key) {
                filesformdata.append(key, value);
            });
            for (var pair of filesformdata.entries()) {
                console.log(pair[0] + ', ' + pair[1]);
                console.log(pair[1]);
            }
            profileService.uploadimage(filesformdata,"POST").then(function(response){
                toastr.success("profilepicture changed");
            });
        }
    }

and here is http request screenshot`

georgeawg
  • 48,608
  • 13
  • 72
  • 95
ebk
  • 305
  • 8
  • 20

2 Answers2

0

use API like

    public async Task<HttpResponseMessage> MethodName()
    {

        if (HttpContext.Current.Request.ContentType == "application/x-www-form-urlencoded")
        {
          var  ParameterName = int.Parse(HttpContext.Current.Request.Form.GetValues("ParameterName")[0].ToString());
        }
        else
        {

            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

        }
         var response = Request.CreateResponse(objreturn);

        return response;
  }
0

When sending non-alphanumeric file or big payload, you should be using form enctype attribute value of "multipart/form-data".

<form enctype="multipart/form-data" ...

Example: HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME

public async Task<HttpResponseMessage> PostFormData()
{
    // Check if the request contains multipart/form-data.
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath("~/App_Data");
    var provider = new MultipartFormDataStreamProvider(root);

    try
    {
        // Read the form data.
        await Request.Content.ReadAsMultipartAsync(provider);

        // This illustrates how to get the file names.
        foreach (MultipartFileData file in provider.FileData)
        {
            Trace.WriteLine(file.Headers.ContentDisposition.FileName);
            Trace.WriteLine("Server file path: " + file.LocalFileName);
        }
        return Request.CreateResponse(HttpStatusCode.OK);
    }
    catch (System.Exception e)
    {
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
    }
}
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
  • i changed my code with above changes. i am getting 415 (Unsupported Media Type). – ebk Jun 02 '18 at 10:31
  • Only now i'm seeing you added Client side code. Then you should pass the `multipart/..` in the headers instead of "undefined". `'content-type': 'multipart/form-data'` – Orel Eraki Jun 02 '18 at 11:18
  • No luck bro.I am suspecting problems with my javascript form appending .but i tested by debugging in console ,its showing it as key value pair,any way i am attaching some more codes and screen shot showing how data is going from client side. – ebk Jun 02 '18 at 13:03
  • Headers are case sensitive, use "Content-Type" – Orel Eraki Jun 02 '18 at 16:09