源码:
public async Task<ListApiResponse<UploadFileResponse>> uploadfile()
{
ListApiResponse<UploadFileResponse> info = new ListApiResponse<UploadFileResponse>();
// 检查是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
info.ErrCode = ErrorCode.Error;
info.ErrMsg = ErrorMessageHelper.NoUpLoadFile;
}
else
{
HttpResponseMessage response = null;
List<UploadFileResponse> UploadFileList = null;
UploadFileResponse Entity = null;
try
{
UploadFileList = new List<Models.Response.Pub.UploadFileResponse>();
// 设置上传目录
var provider = new MultipartFormDataStreamProvider(@"" + dirTempPath + "");
// 接收数据,并保存文件
var bodyparts = await Request.Content.ReadAsMultipartAsync(provider);
if (bodyparts.FileData.Count > 0)
{
foreach (var item1 in bodyparts.FileData)
{
FileInfo fileinfo = new FileInfo(item1.LocalFileName);
string orfilename = item1.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
if (fileinfo.Length <= 0)
{
info.ErrMsg = ErrorMessageHelper.NoUpLoadFile;
info.ErrCode = ErrorCode.apiValidateFail;
}
else if (fileinfo.Length > Convert.ToInt64(FileMaxSize))
{
info.ErrMsg = ErrorMessageHelper.MaxUpLoadFileSize;
info.ErrCode = ErrorCode.apiValidateFail;
}
else if (string.IsNullOrWhiteSpace(fileExt) || !UploadFileType.Contains(fileExt.Substring(1)))
{
info.ErrMsg = ErrorMessageHelper.UpLoadType;
info.ErrCode = ErrorCode.apiValidateFail;
}
else
{
string guid = System.Guid.NewGuid().ToString("N").ToLower();
fileinfo.CopyTo(Path.Combine(dirTempPath, guid + fileExt), true);
Entity = new UploadFileResponse(orfilename, guid + fileExt, FilePathShow + guid + fileExt);
UploadFileList.Add(Entity);
info.ErrCode = ErrorCode.Success;
}
fileinfo.Delete();
}
info.Data = UploadFileList;
}
else
{
info.ErrCode = ErrorCode.Error;
info.ErrMsg = ErrorMessageHelper.NoUpLoadFile;
}
}
catch (Exception ex)
{
info.ErrMsg = ErrorMessageHelper.Fail;
info.ErrCode = ErrorCode.Error;
}
}
return info;
}
配置文件