我有一个看起来像这样的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。我希望我的应用程序做的是上传文件并保留其名称和文件类型。这是这样做的正确方法吗?
所以我发现文件实际上正在上传,如果我添加正确的扩展名,我可以打开它们。任何人都知道如何在上传后保留其文件名?
答案 0 :(得分:0)
想出来
重载了一个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);
}
}
}