ASP.NET MVC 4 Web Api ajax文件上传

Iry*_*yna 8 asp.net-mvc jquery file-upload asp.net-mvc-4 asp.net-web-api

我正在使用asp.net mvc 4 web api开发某种服务.在一个表单上,用户必须上传少量文件,然后将表单提交给服务器.问题是在ajax文件上传到asp.net mvc web api.我已经实现了没有ajax的上传.但我需要用ajax完成它.这是实施

public Task<HttpResponseMessage> PostJob()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
    }

    string path = HttpContext.Current.Server.MapPath(string.Format("~/Resources/Documents"));
    MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(path);
    var request = Request.Content.ReadAsMultipartAsync(provider);

    var task = request.ContinueWith<HttpResponseMessage>(t =>
    {
        if (t.IsFaulted || t.IsCanceled)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }

        string fileName = provider.BodyPartFileNames.FirstOrDefault().Value;
        string originalName = provider.BodyPartFileNames.FirstOrDefault().Key.TrimStart('"').TrimEnd('"');
        string RandomName = provider.BodyPartFileNames.First().Value + Path.GetExtension(originalName);

        FileInfo file = new FileInfo(fileName);
        file.CopyTo(Path.Combine(path, originalName), true);
        file.Delete();


        return new HttpResponseMessage(HttpStatusCode.Created);

    });
Run Code Online (Sandbox Code Playgroud)

我找到了使用HTML5 http://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net-webapi/执行此操作的文章.我需要在IE8中完成这项工作.也许你有任何想法?

感谢任何帮助,Iryna.

Dar*_*rov 14

在旧版浏览器(如IE8)中,您无法使用带有AJAX的纯JavaScript来上传文件.原因是您无权访问用户在文件输入中选择的文件内容.由于您无权访问此内容,因此无法将其发送到服务器.

您可以使用一些现有的文件上传插件:

他们将测试浏览器的功能,如果它支持HTML5和新的XHR2对象,它允许使用AJAX uuploading文件,它将使用它.或者,如果浏览器不支持,则插件可以回退到Flash或隐藏的iframe.因此,如果您需要支持旧版浏览器,您可能没有太多选择,只需使用其他一些客户端脚本技术(如Flash)或使用隐藏的iframe来伪造AJAX请求并实际发送正常的multipart/form-data请求.