文件上传,支持多文件上传,文件重命名
public async Task<HttpResponseMessage> PostFile()
{
HttpResponseMessage responseMessage = new HttpResponseMessage(HttpStatusCode.NotFound);
try
{
List<string> savedFilePath = new List<string>();
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
//检查上传目录
var path = AppDomain.CurrentDomain.BaseDirectory;
string rootPath = System.IO.Path.Combine(path, "upload");
if (!System.IO.Directory.Exists(rootPath)) System.IO.Directory.CreateDirectory(rootPath);
//文件操作
var provider = new MultipartFileStreamProvider(rootPath);
//多文件异步处理
responseMessage = await Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsCanceled || t.IsFaulted)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
foreach (MultipartFileData item in provider.FileData)
{
try
{
//文件上传移动处理
string name = item.Headers.ContentDisposition.FileName.Replace("\"", "");
string newFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(name);
File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));
//将路径加入队列
string fileRelativePath = "/upload/" + newFileName, //相对路径
fileAbsolutePath = rootPath + "\\" + newFileName;//本地文件路径
savedFilePath.Add(fileRelativePath);
}
catch (Exception ex)
{
string message = ex.Message;
}
}
//设置格式
var serializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
serializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
serializerSettings.ContractResolver = new UnderlineSplitContractResolver();
return Request.CreateResponse(HttpStatusCode.Created, JsonConvert.SerializeObject(FrameToResult(savedFilePath), serializerSettings));
});
}
catch (Exception ex)
{
log4net.ILog logger = CustomRollingFileLogger.GetCustomLogger("FileCenterController", "BaseApps");
logger.Error(ex.Message, ex);
}
return responseMessage;
}