4

我使用 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 秒后它会产生错误。

4

3 回答 3

4
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;
});
于 2012-11-29T17:20:28.873 回答
3

IE 9 不支持新的 XMLHttpRequest Level 2(仅 IE10+),这意味着 jquery.form.js 插件使用 iframe 回退。阅读:http ://www.malsup.com/jquery/form/#file-upload由 jquery.form.js 插件的创建者发布。他在那里指出,如果返回数据是 JSON 或 Script,IE 将提示下载。如果您返回 JSON,Jou 必须将内容类型标头强制为“text/html”。

于 2012-12-04T05:41:09.753 回答
1

我也遇到过同样的问题,这个问题只会出现在 IE 中,当你提交一个表单并且它引用的 WebApi 函数返回一些值时。我们还没有一个理想的解决这个问题的方法。

在我们的例子中,我们所做的是将函数拆分为两个调用。第一个函数将详细信息保存在数据库中(假设上传成功),在回调中我们将提交表单以上传文件。webapi 上传函数的返回类型为void. 如果上传失败,我们将在错误回调中处理,然后从数据库中删除相应的条目。

我知道这根本不是一个好的解决方案,但我们已经同意了。

也检查这个问题

于 2012-11-27T08:00:02.527 回答