如何使用jquery和Web API上传文件

时间:2014-05-29 12:18:57

标签: c# jquery asp.net json asp.net-web-api

我正在尝试从jQuery和web api上传文件。如果我只上传文件,它可以工作。如果我向它添加更多数据,它就不起作用。以下是代码; JQuery代码:

<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代码:

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

将HttpPostedFileBase从MVC控制器传递给ApiController也会有所帮助。

1 个答案:

答案 0 :(得分:4)

我不确定我是否回答迟到,但也许这会帮助其他人解决您的问题。

这对我有用:

Html文件/ Mvc查看:

@{
    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控制器:

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

希望这有帮助。