我有其他线程中的bellow代码,但实际上它显示了如何将MultipartFileData文件保存到磁盘。
[HttpPost]
public Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath(Settings.AssetImageTempStorage);
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
// HOW DO I SAVE THIS FILE TO DISK HERE ???
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return task;
}
答案 0 :(得分:23)
以下是在服务器中保存文件的示例。希望这会对你有所帮助。
validate :check_test_id
def check_test_id
date = ( created_at || Date.current ).to_date
if self.class.exists? ["DATE(created_at) = DATE(?) AND test_id = ?", date, test_id]
errors.add :test_id, "is not unique for #{date}"
end
end