发布:2022/5/25 23:06:17作者:管理员 来源:本站 浏览次数:1042
<div></script>
private string uploadPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Upload/";
/// <summary>
/// 上传图片
/// </summary>
/// <returns>成功返回图片URL,失败则返回错误信息</returns>
[HttpPost, Route("UploadPostImgs")]
public string UploadPostImgs()
{
string result = string.Empty;
string imgPath = string.Empty;
HttpRequest request = System.Web.HttpContext.Current.Request;
HttpFileCollection fileCollection = request.Files; // 判断是否有文件
if (fileCollection.Count > 0)
{
// 获取图片文件
HttpPostedFile httpPostedFile = fileCollection[0];
// 文件扩展名
string fileExtension = Path.GetExtension(httpPostedFile.FileName);
// 图片名称
string fileName = Guid.NewGuid().ToString() + fileExtension;
// 图片上传路径
string filePath = uploadPath + fileName;
// 验证图片格式
if (fileExtension.Contains(".jpg")
|| fileExtension.Contains(".png")
|| fileExtension.Contains(".bmp"))
{
// 如果目录不存在则要先创建
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
// 保存新的图片文件
while (File.Exists(filePath))
{
fileName = Guid.NewGuid().ToString() + fileExtension;
filePath = uploadPath + fileName;
}
httpPostedFile.SaveAs(filePath);
// 把文件的存储路径保存起来
// 返回图片URL
imgPath = fileName;
result = imgPath;
}
else
{
result = "请选择jpg/png/bmp格式的图片";
}
}
else
{
result = "请先选择图片!";
}
return result;
}
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4