0

I am trying to upload file using formdata object create in angularjs

 var formdata = new FormData();
    formdata.append("imagefile", file)

    $http.post('api/upload', formdata, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } });

want code for c# controller code using webapi2 in mvc 6

1 Answer 1

4
var fd = new FormData();
    fd.append('file', $scope.teamLogo);
    fd.append('aa', 'a');
    $http.post('http://localhost:51815/api/upload/', fd, {
        transformRequest: saangular.identity,
        headers: { 'Content-Type': undefined }
    }).then(function (teamList) { });

in Controller

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);
        }
    }

use this code in js file

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.