![](/img/trans.png)
[英]Uploading and receiving large files http-compressed with ASP.NET gives “unexpected end of mime multipart stream”
[英]Uploading something as Mime Multipart
我有一個看起來像這樣的C#控制器
public class UploadController : ApiController
{
public async Task<HttpResponseMessage> Post()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/Uploads");
var provider = new MultipartFormDataStreamProvider(root);
try
{
StringBuilder sb = new StringBuilder(); // Holds the response body
// Read the form data and return an async task.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
sb.Append(string.Format("{0}: {1}\n", key, val));
}
}
// This illustrates how to get the file names for uploaded files.
foreach (var file in provider.FileData)
{
FileInfo fileInfo = new FileInfo(file.LocalFileName);
sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));
}
return new HttpResponseMessage()
{
Content = new StringContent(sb.ToString())
};
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
還有一個看起來像這樣的Upload.html頁面
**<form name="form1" method="post" enctype="multipart/form-data" action="api/Upload">
<div>
<label for="caption">Image Caption</label>
<input name="caption" type="text" />
</div>
<div>
<label for="image1">Image File</label>
<input name="image1" type="file" />
</div>
<div>
<input ng-click="submit()" type="submit" value="Submit" />
</div>
**
它使我可以選擇一個文件,然后單擊“上傳”,然后將其保存到本地文件夾。 但是,上傳后,這些文件稱為“ BodyPart_175b76cb-88f2-4ea4-bbc5-fd3038345e5e”之類的文件,其類型為file。 我希望我的應用程序執行的操作是上傳文件並保留其名稱和文件類型。 這是這樣做的正確方法嗎?
因此,我發現文件實際上正在上載,如果添加正確的擴展名,則可以打開它們。 有人對上傳后如何保留其文件名有任何想法嗎?
弄清楚了
重載了其中一個MIME對象以正確的名稱返回
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
namespace AngularFun.Controllers
{
class MyMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public MyMultipartFormDataStreamProvider(string path)
: base(path)
{
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
string fileName;
if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName))
{
fileName = headers.ContentDisposition.FileName;
}
else
{
fileName = Guid.NewGuid().ToString() + ".data";
}
return fileName.Replace("\"", string.Empty);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.