问题描述
我已经创建使用ASP.NET的WebAPI的文件上传的方法,下面的code:
[DataContract]
公共类FileDesc
{
[数据成员]
公共字符串名称{;组; } [数据成员]
公共字符串URL {搞定;组; } [数据成员]
众长尺寸{搞定;组; } [数据成员]
公共字符串UniqueFileName {搞定;组; } [数据成员]
公众诠释ID {搞定;组; } [数据成员]
公众的DateTime modifiedon {搞定;组; } [数据成员]
公共字符串描述{搞定;组; }
公共FileDesc(字符串使用rootUrl,FileInfo的楼诠释PID,串aFileName)
{
ID = PID;
名称= aFileName;
UniqueFileName = f.Name;
URL =使用rootUrl +/文件/+ f.Name;
大小= f.Length / 1024;
modifiedon = f.LastWriteTime;
说明= aFileName;
}
} 公共类CustomMultipartFormDataStreamProvider:MultipartFormDataStreamProvider
{
//字符串uniqueFileName =的String.Empty; 公共字符串UniqueFileName
{
得到;
组;
}
公共字符串ActualFileName
{
得到;
组;
} 公众诠释的TaskID {搞定;组; }
私人诠释用户名{搞定;组; }
公共CustomMultipartFormDataStreamProvider(字符串路径,INT ptaskID,诠释pUserID)
:基地(路径)
{
的TaskID = ptaskID;
用户名= pUserID;
} 公众覆盖字符串GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders头)
{
变量名称=!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,用户名); headers.Add(ActualFileName,ActualFileName);
headers.Add(ID,id.ToString()); 返回UniqueFileName; }
}
[授权]
公共类FileUploadController:ApiController
{ 私人字符串StorageRoot
{
{返回Path.Combine(System.Web.HttpContext.Current.Server.MapPath(〜/文件/)); } //应该路径!总是以结束'/'
}
公共任务<&IEnumerable的LT; FileDesc>>邮政(INT ID)
{ 字符串FOLDERNAME =文件;
串PATH = HttpContext.Current.Server.MapPath(〜/+ FOLDERNAME);
字符串使用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的; 如果(Request.Content.IsMimeMultipartContent())
{
VAR streamProvider =新CustomMultipartFormDataStreamProvider(PATH,ID,BEL_PMS.Utilities.FormsAuthenticationUtil.GetCurrentUserID);
VAR任务= Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t = GT;
{ 如果(t.IsFaulted || t.IsCanceled)
{
抛出新的Htt presponseException(的HTTPStatus code.InternalServerError);
} VAR的fileInfo = streamProvider.FileData.Select(I =&GT;
{ VAR信息=新的FileInfo(i.LocalFileName);
INT写到FileID = Convert.ToInt32((从i.Headers H其中h.Key ==ID选择h.Value.First())FirstOrDefault());
字符串ActualFileName =(从i.Headers H其中h.Key ==ActualFileName选择h.Value.First())FirstOrDefault()。
返回新FileDesc(使用rootUrl,资讯,写到FileID,ActualFileName);
});
返回的fileInfo;
});
//返回新的Htt $ P $ {psponseMessage状态code = System.Net.HttpStatus code.OK,内容=任务};
返回任务;
}
其他
{
抛出新的Htt presponseException(Request.CreateResponse(的HTTPStatus code.NotAcceptable,这个请求的格式不正确));
} }
}
和使用jquery.form.js插件,通过Ajax上传文件,下面是code:
$('#frmmultiupload')。当作ajaxForm({
成功:OnUploadedSuccessfully,
错误:函数(X,Y){
MESG(发生错误,而上传文件!请确保总文件大小小于4 MB,然后再试一次。,
'错误','文件上传失败。');
}
});
一切工作的文件,但它创造了IE9的问题
IE浏览器说你想打开或从本地主机救?
下面是网络跟踪:
我发现了一些线索here不是不知道如何转换任务&LT; IEnumerable的&LT; FileDesc&GT;&GT;
到任务&LT; Htt的presponseMessage&GT;
。
我指定的ajaxSetup 30秒超时,所以它产生误差30秒后。
VAR任务= Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith&LT; Htt的presponseMessage&GT;(T =&GT ;
{
如果(t.IsFaulted || t.IsCanceled)
{
抛出新的Htt presponseException(的HTTPStatus code.InternalServerError);
} VAR的fileInfo = streamProvider.FileData.Select(I =&GT;
{ VAR信息=新的FileInfo(i.LocalFileName);
INT写到FileID = Convert.ToInt32((从i.Headers H其中h.Key ==ID选择h.Value.First())FirstOrDefault());
字符串ActualFileName =(从i.Headers H其中h.Key ==ActualFileName选择h.Value.First())FirstOrDefault()。
返回新FileDesc(使用rootUrl,资讯,写到FileID,ActualFileName);
});
VAR响应= Request.CreateResponse(的HTTPStatus code.OK,的fileInfo);
response.Content.Headers.ContentType =新MediaTypeHeaderValue(text / html的);
返回响应;
});
I have created a file upload method using ASP.NET WEBAPI, below the code:
[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"));
}
}
}
and uploading files via Ajax using jquery.form.js plugin, below is the code:
$('#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.');
}
});
everything works file but it is creating problem in IE9
IE says "Do you want to open or save from local host?"
Below is the network trace:I found some hint here not don't know how to convert Task<IEnumerable<FileDesc>>
to Task<HttpResponseMessage>
.
I have specified timeout of 30 sec in ajaxSetup, so after 30 sec it is generating error.
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;
});
这篇关于ASP.NET的WebAPI文件上传,问题同IE9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!