MultipartFormDataStreamProvider并追加到现有文件
本文关键字:文件 追加 MultipartFormDataStreamProvider | 更新日期: 2023-09-27 18:15:44
大家好,
我使用ASP.net WebApi来接收来自Cordova应用程序的上传(通过HTTP多部分POST请求发送)。上传是"块",因此,我需要在第一个块上创建一个文件,然后将每个后续的"块"附加到它。以下是我目前正在处理的内容:
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path)
{ }
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName";
return name.Replace("'"", string.Empty); //this is here because Chrome submits files in quotation marks which get treated as part of the filename and get escaped
}
}
和控制器中…
[Route("upload"), HttpGet, HttpPost]
public void HandleUpload()
{
string root = HttpContext.Current.Server.MapPath("~/App_Data/upload-temp");
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new Libs.CustomMultipartFormDataStreamProvider(root);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
});
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
我假设在CustomMultipartFormDataStreamProvider我会以某种方式覆盖GetStream来完成追加,但对于我的生活不能得到我的头围绕它…
有没有人知道如何做到这一点?
欢呼:)
这篇文章正是我正在处理的问题,诀窍是在您的自定义MultipartFormDataStreamProvider中重写GetStream方法。我的解决方案基于System.Net.Http.MultipartFormDataStreamProvider提供程序的源代码。
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) {
if (!headers.ContentDisposition.FileName.HasValue())
return Stream.Null;
if (parent == null)
throw new ArgumentNullException("parent");
if (headers == null)
throw new ArgumentNullException("headers");
var fileName = this.GetLocalFileName(headers);
if (!fileName.HasValue())
throw new ArgumentNullException("fileName");
var file = Path.Combine(this.RootPath, fileName);
this.FileData.Add(new MultipartFileData(headers, file));
// the key is appending a file as opposed to just creating it - the original ms implementation is:
// return File.Create(file, this.BufferSize, FileOptions.Asynchronous)
return new FileStream(file, FileMode.Append, FileAccess.Write, FileShare.Write, this.BufferSize, true);}