C# 4.0 将MultipartFileData文件保存到磁盘
我有下面的代码,我在这里的其他线程中也看到过,但是它没有真正展示如何在拥有MultipartFileData文件后将其保存到磁盘C# 4.0 将MultipartFileData文件保存到磁盘,c#-4.0,multipart,multifile-uploader,C# 4.0,Multipart,Multifile Uploader,我有下面的代码,我在这里的其他线程中也看到过,但是它没有真正展示如何在拥有MultipartFileData文件后将其保存到磁盘 [HttpPost] public Task<HttpResponseMessage> PostFormData() { // Check if the request contains multipart/form-data. if (!Request.Content.IsMimeMultipartContent()) {
[HttpPost]
public Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath(Settings.AssetImageTempStorage);
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
// HOW DO I SAVE THIS FILE TO DISK HERE ???
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return task;
}
[HttpPost]
公共任务PostFormData()
{
//检查请求是否包含多部分/表单数据。
如果(!Request.Content.IsMimeMultipartContent())
{
抛出新的HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root=HttpContext.Current.Server.MapPath(Settings.AssetImageTempStorage);
var provider=新的MultipartFormDataStreamProvider(根);
//读取表单数据并返回异步任务。
var task=Request.Content.ReadAsMultipartAsync(提供程序)。
继续(t=>
{
如果(t.IsFaulted | | t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError,t.Exception);
}
//这说明了如何获取文件名。
foreach(provider.FileData中的MultipartFileData文件)
{
//如何在此处将此文件保存到磁盘???
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine(“服务器文件路径:“+file.LocalFileName”);
}
返回Request.CreateResponse(HttpStatusCode.OK);
});
返回任务;
}
以下是在服务器中保存文件的示例。希望这对你有帮助
public class TestController : ApiController
{
const string StoragePath = @"T:\WebApiTest";
public async Task<HttpResponseMessage> Post()
{
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new MultipartFormDataStreamProvider(Path.Combine(StoragePath, "Upload"));
await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (MultipartFileData fileData in streamProvider.FileData)
{
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
}
string fileName = fileData.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(@"/") || fileName.Contains(@"\"))
{
fileName = Path.GetFileName(fileName);
}
File.Move(fileData.LocalFileName, Path.Combine(StoragePath, fileName));
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
else
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
}
}
公共类TestController:ApiController
{
常量字符串StoragePath=@“T:\WebApiTest”;
公共异步任务Post()
{
if(Request.Content.IsMimeMultipartContent())
{
var streamProvider=new MultipartFormDataStreamProvider(Path.Combine(StoragePath,“Upload”);
wait Request.Content.ReadAsMultipartAsync(streamProvider);
foreach(streamProvider.fileData中的MultipartFileData文件数据)
{
if(string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable,“此请求未正确格式化”);
}
字符串文件名=fileData.Headers.ContentDisposition.fileName;
if(fileName.StartsWith(“\”)和&fileName.EndsWith(“\”)
{
fileName=fileName.Trim(“”);
}
if(fileName.Contains(@“/)| | fileName.Contains(@“\”))
{
fileName=Path.GetFileName(fileName);
}
Move(fileData.LocalFileName,Path.Combine(StoragePath,fileName));
}
}
返回Request.CreateResponse(HttpStatusCode.OK);
}
其他的
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable,“此请求未正确格式化”);
}
}
你们看问题了吗?有一行是File.Copy(fileData.LocalFileName,Path.Combine(StoragePath,fileName))
我想,它会将收到的文件复制到特定位置。感谢mozgow,我以类似的方式实现了它。现在工作正常,但在IE8和IE9中,我得到的响应是:HTTP/1.1 415不支持的媒体类型。在IE10中,我很好,但低于此值,我收到了这个愚蠢的错误,根本不确定原因。抱歉,发现了问题。我使用的是blueimp文件uploader。它附带了一个iframe JS文件,适用于较旧的浏览器,但我没有包含。我现在已经包含了它,它工作正常。user2520440早已不存在了,但代码中的问题是:“如何将此文件保存到此处的磁盘?”答案很简单:您不需要。它已保存在.ReadAsMultipartAsync()中,这就是触发保存的原因。我在File.Move(fileData.LocalFileName,Path.Combine(StoragePath,fileName));
偶尔出现“File in use”异常时遇到问题。@enrol76很抱歉回复太晚。我想不应该出现“File in use”异常。但是,如果出现此异常,可以尝试File.Copy()而不是File.Move()。因为,即使源文件被另一个进程.System.IO.File.Copy(@“E:\asd.txt”,@“F:\asd\u Copy.txt”,true)使用,也会执行方法File.Copy();在客户端(.NET)哪里可以找到上传数据的方法?@Shimmy抱歉,我没有听到你的问题?@Shimmy哦,抱歉。我无法回答这个问题,因为我没有尝试过任何其他类型。如果你能尝试一下,并与我们分享你的宝贵结论,这将对所有人都非常有帮助。