ASP.NET的WebAPI文件上传,问题与IE9(ASP.NET WEBAPI file uplo

2019-07-04 03:50发布

我创建使用ASP.NET的WebAPI文件上传的方法,下面的代码:

[DataContract]
    public class FileDesc
    {
        [DataMember]
        public string name { get; set; }      

        [DataMember]
        public string url { get; set; }

        [DataMember]
        public long size { get; set; }

        [DataMember]
        public string UniqueFileName { get; set; }

        [DataMember]
        public int id { get; set; }

        [DataMember]
        public DateTime modifiedon { get; set; }

        [DataMember]
        public string description { get; set; }


        public FileDesc(string rootUrl, FileInfo f,int pId, string aFileName)
        {
            id = pId;
            name = aFileName;
            UniqueFileName = f.Name;
            url = rootUrl + "/Files/" + f.Name;
            size = f.Length / 1024;
            modifiedon = f.LastWriteTime;
            description = aFileName;
        }
    }

    public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        //string uniqueFileName = string.Empty;

        public string UniqueFileName
        {
            get;
            set;
        }
        public string ActualFileName
        {
            get;
            set;
        }

        public int TaskID { get; set; }
        private int UserID { get; set; }
        public CustomMultipartFormDataStreamProvider(string path, int ptaskID, int pUserID)
            : base(path)
        {
            TaskID = ptaskID;
            UserID = pUserID;
        }

        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName";

            ActualFileName = name.Replace("\"", string.Empty);

            ActualFileName = Path.GetFileName(ActualFileName);

            UniqueFileName = Guid.NewGuid().ToString() + Path.GetExtension(ActualFileName);

            int id = SaveFileInfoIntoDatabase(ActualFileName, TaskID, UniqueFileName, UserID);

            headers.Add("ActualFileName", ActualFileName);
            headers.Add("id", id.ToString());

            return UniqueFileName;

        }   
    }
    [Authorize]
    public class FileUploadController : ApiController
    {

        private string StorageRoot
        {
            get { return Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Files/")); } //Path should! always end with '/'
        }


        public Task<IEnumerable<FileDesc>> Post(int id)        
        {

            string folderName = "Files";
            string PATH = HttpContext.Current.Server.MapPath("~/" + folderName);
            string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
            HttpContext.Current.Response.BufferOutput = true;
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentType = "text/html";

            if (Request.Content.IsMimeMultipartContent())
            {
                var streamProvider = new CustomMultipartFormDataStreamProvider(PATH, id, BEL_PMS.Utilities.FormsAuthenticationUtil.GetCurrentUserID);
                var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t =>
                {

                    if (t.IsFaulted || t.IsCanceled)
                    {
                        throw new HttpResponseException(HttpStatusCode.InternalServerError);
                    }

                    var fileInfo = streamProvider.FileData.Select(i =>
                    {

                        var info = new FileInfo(i.LocalFileName);
                        int FileID = Convert.ToInt32((from h in i.Headers where h.Key =="id" select h.Value.First()).FirstOrDefault());
                        string ActualFileName = (from h in i.Headers where h.Key =="ActualFileName" select h.Value.First()).FirstOrDefault();
                        return new FileDesc(rootUrl, info, FileID, ActualFileName);
                    });
                    return fileInfo;
                });


                //return new HttpResponseMessage { StatusCode = System.Net.HttpStatusCode.OK, Content = task};               
                return task;
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
            }

        }
}

并使用jquery.form.js插件通过Ajax上传文件,下面是代码:

$('#frmmultiupload').ajaxForm({
            success: OnUploadedSuccessfully,            
            error: function (x, y) {
                mesg('Error occured while file upload! Please make sure that total file size is less than 4 MB and try again.',
                    'error', 'File upload failed.');
            }
        });

一切正常文件,但它是在IE9创设问题

IE说,“你想打开或从本地主机救?”

下面是网络跟踪: 我发现了一些线索在这里不是不知道如何转换Task<IEnumerable<FileDesc>>Task<HttpResponseMessage>

我已指定在ajaxSetup 30秒的超时时间,所以也产生误差30秒后。

Answer 1:

var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<HttpResponseMessage>(t =>
{
    if (t.IsFaulted || t.IsCanceled)
    {
        throw new HttpResponseException(HttpStatusCode.InternalServerError);
    }

    var fileInfo = streamProvider.FileData.Select(i =>
    {

        var info = new FileInfo(i.LocalFileName);
        int FileID = Convert.ToInt32((from h in i.Headers where h.Key =="id" select h.Value.First()).FirstOrDefault());
        string ActualFileName = (from h in i.Headers where h.Key =="ActualFileName" select h.Value.First()).FirstOrDefault();
        return new FileDesc(rootUrl, info, FileID, ActualFileName);
    });
    var response = Request.CreateResponse(HttpStatusCode.OK, fileInfo);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
});


Answer 2:

IE 9不支持新的XMLHttpRequest 2级(仅IE10 +),这意味着jquery.form.js插件使用的IFRAME回退。 阅读: http://www.malsup.com/jquery/form/#file-upload刊登的jquery.form.js插件的创造者。 他指出那里,IE会提示下载,如果返回的数据是JSON或脚本。 柔必须强制内容类型标题为“text / html的”如果回到JSON。



Answer 3:

我也遇到同样的问题,那这个问题将在您提交的形式和它引用的回报一些value.We还没有得到这个问题的理想解决方案的WebAPI功能发生只在IE浏览器。

在我们的情况下,我们所做的是在分裂的功能,两个呼叫。 第一个函数将保存在数据库中(假设上传成功)的详细信息,并在回调,我们将提交表单上传的文件。 在的WebAPI上传函数的返回类型为void 。 如果上传失败,我们会处理,在错误回调,然后从数据库中删除相应的条目。

我知道这是不是一个很好的修复可言,但我们不得不去用它。

检查这个问题为好。



文章来源: ASP.NET WEBAPI file upload, issues with IE9