1

I am trying to upload a file from jQuery and web api. If I upload only file, it works. If I add some more data to it, it do not work. Below is the code; JQuery code :

<script type="text/javascript">
        $(document).ready(function () {
            $("#button1").click(OnUpload);
        });

        function OnUpload(evt) {
            //var files = $("#file1").get(0).files;
            var request = {
                Name: "test",
                Address: "address",
                Description: "desc",
                City: "city",
                files:$("#file1").get(0).files
            };

            var jsonData = JSON.stringify(request);

            if (files.length > 0) {
                if (window.FormData !== undefined) {
                    var data = new FormData();
                    for (i = 0; i < files.length; i++) {
                        data.append("file" + i, files[i]);
                    }
                    $.ajax({
                        type: "POST",
                        url: "http://localhost:51801/api/FileUpload/",
                        contentType: false,
                        processData: false,
                        data: jsonData + files,
                        success: function (results) {
                            for (i = 0; i < results.length; i++) {
                                alert(results[i]);
                            }
                        }
                    });
                } else {
                    alert("This browser doesn't support HTML5 multiple file uploads!");
                }
            }
        }
    </script>

C# Web API code:

public HttpResponseMessage Post(RequestP req)
        {
            HttpResponseMessage result = null;
            var httpRequest = 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("~/" + postedFile.FileName);
                    postedFile.SaveAs(filePath);

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

public class RequestP
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string Description { get; set; }
        public string City { get; set; }
        public List<HttpPostedFileBase> files { get; set; }
    }

Passing HttpPostedFileBase from MVC controller to ApiController will also help.

5
  • refer stackoverflow.com/questions/21497944/file-upload-jquery-webapi Commented May 29, 2014 at 12:43
  • In controller method, how to access other form data ? Commented May 29, 2014 at 12:50
  • I can't see that you are sending formData Commented May 29, 2014 at 13:04
  • Please check request object. I am trying to send files to be uploaded and some other fields as well. Commented May 29, 2014 at 13:16
  • 1
    Please down vote carefully, the reference question is partially answered. Commented May 29, 2014 at 13:24

1 Answer 1

4

I am not sure if I am answering late, but maybe this will help someone else with your problem.

This is what worked for me:

Html file/Mvc View:

@{
    ViewBag.Title = "Home Page";
}

<label for="txtFile">Upload file: </label>
<input type="file" id="txtFile" name="file" />
<br />
<a href="#" id="lnkUploadFile">Upload File</a>

<script>
    $(function ()
    {
        var $txtFile = $('#txtFile'),
            files;
        var data = new FormData();
        $('#lnkUploadFile').click(function ()
        {
            uploadFile();
        });

        function uploadFile()
        {
            if ($txtFile.length)
            {
                files = $txtFile[0].files;
                data.append("UploadedImage", files[0]);
                data.append("ImageName", 'MyImage');
            }

            $.ajax({
                type: "POST",
                url: "/api/FileUpload/",
                contentType: false,
                processData: false,
                data: data
            }).then(function () { });
        }


    });

</script>

Web Api Controller:

namespace MvcApplication1.Controllers
{
    public class FileUploadController : ApiController
    {
        // POST api/fileupload
        public void Post()
        {
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                // Get the uploaded image from the Files collection
                var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];

                if (httpPostedFile != null)
                {
                    // Get the complete file path
                    String fileSavePath = HttpContext.Current.Server.MapPath("~/Content/Images/") + HttpContext.Current.Request.Form["ImageName"].ToString();

                    // Save the uploaded file to "UploadedFiles" folder
                    httpPostedFile.SaveAs(fileSavePath);
                }
            }
        }        
    }
}

Hope this helps.

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.