/// <summary>
/// 图片上传 [FromBody]string type
/// 单个图片最大支持200KB
///
/// </summary>
/// <returns></returns>
[HttpPost]
public JsonResult ImgUpload()
{
var result = new List<ImgUploadResult>();
// 定义允许上传的文件扩展名
const string fileTypes = "gif,jpg,jpeg,png,bmp";
// 最大文件大小(200KB)
const int maxSize = 205000;
// 获取附带POST参数值
var type = Request["type"];
// 设置上传目录
var imgPath = "";
switch (type)
{
case "file":
imgPath = ConfigurationManager.AppSettings["HouseImgPath"];
break;
case "video":
imgPath = ConfigurationManager.AppSettings["HouseVideoPath"];
break;
case "information":
imgPath = ConfigurationManager.AppSettings["InformationPath"];
break;
}
// 存储文件服务器IP(内网)
string fileComputerIP = ConfigurationManager.AppSettings["FileComputerIP"];
for (var fileId = 0; fileId < Request.Files.Count; fileId++)
{
var curFile = Request.Files[fileId];
if (curFile.ContentLength < 1) {continue;}
else if (curFile.ContentLength > maxSize)
{
return this.JsonFormatError("上传文件中有图片大小超出200KB!");
}
var fileExt = Path.GetExtension(curFile.FileName);
if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
{
return this.JsonFormatError("上传文件中包含不支持文件格式!");
}
else
{
// 存储文件名
string fullFileName = type + "_" + DateTime.Now.ToString("yyyyMMddhhmmssff") + CreateRandomCode(8) + fileExt;
// 存储路径(绝对路径)
string virtualPath = string.Format(@"\\{0}\{1}\{2}", fileComputerIP, imgPath, fullFileName);
try
{
curFile.SaveAs(virtualPath);
// 文件服务器端口号IP
string fileComputerIPPort = ConfigurationManager.AppSettings["FileComputerIPNumber"];
result.Add(new ImgUploadResult()
{
FullFileName = fullFileName,
ImgUrl = string.Format(@"http://{0}/{1}/{2}", (fileComputerIP + ":" + fileComputerIPPort), imgPath, fullFileName)
});
}
catch (Exception exception)
{
throw new Exception("上传失败!", exception);
}
}
}
return this.JsonFormatSuccess(result);
}
/// <summary>
/// 生成指定长度的随机码。
/// </summary>
private string CreateRandomCode(int length)
{
string[] codes = new string[36] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
StringBuilder randomCode = new StringBuilder();
Random rand = new Random();
for (int i = 0; i < length; i++)
{
randomCode.Append(codes[rand.Next(codes.Length)]);
}
return randomCode.ToString();
}
- 1
- 2
- 3
- 4
- 5
- 6
前往页