我有一个看起来像这样的 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”,它是文件类型。我希望我的应用程序做的是上传文件并保留其名称和文件类型。这是这样做的正确方法吗。
编辑
所以我发现文件实际上正在上传,如果我添加正确的扩展名,我就可以打开它们。任何人都知道如何使它在上传后保留其文件名?