/// <summary>
/// 上传图片
/// </summary>
/// <returns>成功返回图片URL,失败则返回错误信息</returns>
[HttpPost]
public BaseResponse<string> Upload()
{
try
{
var content = Request.Content;
var tempUploadFiles = "/Upload/TempUploadFiles/";
var newFileName = "";
string filePath = "";
string extname = "";
string returnurl = "";
var sp = new MultipartMemoryStreamProvider();
Task.Run(async () => await Request.Content.ReadAsMultipartAsync(sp)).Wait();
foreach (var item in sp.Contents)
{
if (item.Headers.ContentDisposition.FileName != null)
{
var filename = item.Headers.ContentDisposition.FileName.Replace("\"", "");
FileInfo file = new FileInfo(filename);
string fileTypes = "gif,jpg,jpeg,png,bmp";
if (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) == -1)
{
throw new ApplicationException("不支持上传文件类型");
}
//if (file.Length> 5242880)
//{
// throw new UserFriendlyException(L("文件过大"));
//}
extname = filename.Substring(filename.LastIndexOf('.'), (filename.Length - filename.LastIndexOf('.')));
newFileName = Guid.NewGuid().ToString().Substring(0, 6) + extname;
string newFilePath = DateTime.Now.ToString("yyyy-MM-dd") + "/";
if (!Directory.Exists(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath))
{
Directory.CreateDirectory(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath);
}
filePath = Path.Combine(HostingEnvironment.MapPath("/") + tempUploadFiles + newFilePath, newFileName);
returnurl = Path.Combine(tempUploadFiles + newFilePath, newFileName);
var ms = item.ReadAsStreamAsync().Result;
using (var br = new BinaryReader(ms))
{
if (ms.Length > 1048576 * 5)
{
//throw new UserFriendlyException(L("文件过大"));
}
var data = br.ReadBytes((int)ms.Length);
File.WriteAllBytes(filePath, data);
}
}
}
// return returnurl;
return new BaseResponse<string> { Success = true, Data = returnurl };
}
catch (Exception ex)
{
return new BaseResponse<string> { Success = false, Data = ex.Message, Code = 1 };
}
}
在web.config文件的<system.webserver></system.webserver>节点下添加跨域设置
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Max-Age" value="30"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
</customHeaders>
</httpProtocol>