1
我試圖將圖像的文件名更改爲我張貼在輸入框username
中的值。這些文件正在上傳到服務器,並且在覆蓋GetLocalFileName
之後,文件名稱從「BodyPart_(xyz)」更改爲原始文件。如何將它們重命名爲我在輸入框中提供的值?ASP.NET WebAPI更改文件名?
<form name="form1" method="post" enctype="multipart/form-data" action="api/poster/postformdata">
<div class="row-fluid fileform">
<div class="span3"><strong>Username:</strong></div>
<input name="username" value="test" type="text" readonly/>
</div>
<div class="row-fluid fileform">
<div class="span3"><strong>Poster:</strong></div>
<div class="span4"><input name="posterFileName" ng-model="posterFileName" type="file" /></div>
</div>
<div class="row-fluid fileform">
<div class="span8"><input type="submit" value="Submit" class="btn btn-small btn-primary submitform" /></div>
</div>
</form>
我已經存儲了我的newName
變量收到的價值,但我對如何重命名服務器上的文件混淆。
public async Task<HttpResponseMessage> PostFormData()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
// Show all the key-value pairs.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Trace.WriteLine(string.Format("{0}: {1}", key, val));
newName = val;
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public 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);
}
}
非常感謝。我無法弄清楚如何使用新名稱複製文件並刪除舊文件。我如何在'ExecutePostProcessingAsync()'本身實現它? – magnum