【问题标题】:How to upload file using jquery and Web API如何使用 jquery 和 Web API 上传文件
【发布时间】:2014-05-29 12:18:57
【问题描述】:

我正在尝试从 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 也会有所帮助。

【问题讨论】:

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


【解决方案1】:

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

这对我有用:

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2012-11-24
    • 2016-07-02
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 2015-07-07
    • 2015-05-22
    相关资源
    最近更新 更多