我使用以下代码来接收上传的文件并将它们存储在服务器上的uploadedFiles文件夹中。
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path) { }
public override string GetLocalFileName(HttpContentHeaders headers)
{
return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
}
}
[HttpPost]
public async Task<HttpResponseMessage> ReceiveFileupload()
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
// Prepare CustomMultipartFormDataStreamProver in which our multipart form data will be loaded
string fileSaveLocation = HttpContext.Current.Server.MapPath("~/UploadedFiles");
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
List<string> files = new List<string>();
Duck duck = null;
try
{
// Read all contents of multipart message into CustomMultipartFormDataStreamProvider
await Request.Content.ReadAsMultipartAsync(provider);
// Parse an ID which is passed in the form data
long id;
if (!long.TryParse(provider.FormData["id"], out id))
{
return Request.CreateResponse(HttpStatusCode.ExpectationFailed, "Couldn't determine id.");
}
duck = db.Ducks.Find(id);
if (null == duck)
return Request.CreateResponse(HttpStatusCode.NotAcceptable, "Duck with ID " + id + " could not be found.");
// Loop through uploaded files
foreach (MultipartFileData file in provider.FileData)
{
// File ending needs to be xml
DoSomething();
// On success, add uploaded file to list which is returned to the client
files.Add(file.LocalFileName);
}
// Send OK Response along with saved file names to the client.
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (System.Exception e) {
return Request.CreateResponse(HttpStatusCode.InternalServerError, e);
}
}
现在我想重命名上传的文件。据我了解,存储和重命名必须在关键部分完成,因为当另一个用户同时上传同名文件时,第一个文件将被覆盖。
这就是我想象的解决方案,但是 await
不允许出现在 lock 语句中。
lock(typeof(UploadController)) {
await Request.Content.ReadAsMultipartAsync(provider); //That's the line after which the uploaded files are stored in the folder.
foreach (MultipartFileData file in provider.FileData)
{
RenameFile(file); // Rename according to file's contents
}
}
我如何保证文件将自动存储和重命名?
与其使用原始名称然后重命名,不如在上传代码中即时生成一个名称?
例如如果文件显示为“foo.xml
”,您将其作为“BodyPart_be42560e-863d-41ad-8117-e1b634e928aa
”写入磁盘?
另请注意,如果您将文件上传到 "~/UploadedFiles"
,任何人都可以使用 www.example.com/UploadedFiles/name.xml 这样的 URL 下载它
- 您应该将文件存储在 ~/App_Data/
中以防止出现这种情况。
更新:
为什么不删除您对 GetLocalFileName
方法的重写,并简单地使用 MultipartFileStreamProvider 中的原始方法?基类?
public virtual string GetLocalFileName(HttpContentHeaders headers)
{
if (headers == null)
{
throw Error.ArgumentNull("headers");
}
return String.Format(CultureInfo.InvariantCulture, "BodyPart_{0}", Guid.NewGuid());
}
这应该将每个文件保存为唯一名称,而无需稍后重命名。
我是一名优秀的程序员,十分优秀!