分别为MVC和webapi版本的图片上传接口
//图片和表单一起提交的方式(MVC)
public ActionResult FileUpload()
{
var callback = new ApiResultMsg() { Msg = "上传失败!", Code = -1 };
if (HttpContext.Request.Files.Count > 0)//过滤表单是否有上传文件
{
HttpPostedFileBase file = HttpContext.Request.Files["FileName"];//获取前端文件上传控件Name名
string filePath = string.Empty; //上传成功后返回的新文件存放路径
if (file.ContentLength != 0) //二次过滤,过滤是否选择有效上传文件
{
string extension = Path.GetExtension(file.FileName).ToLower(); //获取上传文件后缀名并转换为小写字母
if (".jpg.gif.png.jpeg".Contains(extensi//下面可对文件类型进行限制等等...等...
{
filePath = Misc.UploadFile(file,"/Images/",".jpg.gif.png.jpeg");
}
else
{
filePath = Misc.UploadFile(file,"/Resource/",".doc.docx.xls.xlsx.txt.pdf.ppt.rar.mp3.mp4.zip.avi");
}
}
//下面是也是一种文件保存的方式,假设客户端有多个file提交
HttpPostedFileBase headPic = HttpContext.Request.Files["HeadPic"];//获取intput file的name的文件
if (headPic.ContentLength > 0) //二次过滤
{
Stream uploadStream = headPic.InputStream;//这里可以看到文件流
String fileName = headPic.FileName;//获取上传文件名
String fileExt = Path.GetExtension(fileName).ToLower();//获取上传文件名后缀
String DirCurr = @"/Images/UserHeadPic/";//文件存放目录
if (!Directory.Exists(HttpContext.Server.MapPath(DirCurr)))//判断当前环境是否存在该路径
{
Directory.CreateDirectory(HttpContext.Server.MapPath(DirCurr));//创建新文件路径
}
String saveUrl = HttpContext.Server.MapPath(DirCurr);//映射绝对路径
String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
DirCurr += ymd + "/";
saveUrl += ymd + "/";
if (!Directory.Exists(saveUrl))
{
Directory.CreateDirectory(saveUrl);
}
String newFileName = Misc.MaxCharacters(System.Guid.NewGuid().ToString(), 5) + "-" + Misc.MaxCharacters(Misc.ClearFilename(fileName.Replace(fileExt, "")), 20) + fileExt;
String ImgfilePath = saveUrl + newFileName;
DirCurr += newFileName;
headPic.SaveAs(ImgfilePath);
}
}
}
///
/// 普通图片上传 生成一张图片(webApi)
///
/// 返回带域名得绝对路径
[HttpPost]
[AllowAnonymous]
public IHttpActionResult UploadImg_SaveFile(string FoldName = "Product")
{
string showData = Misc.ConvertToShortDateTime(System.DateTime.Now, "yyyy-MM-dd");
ApiResultMsg apiResult = new ApiResultMsg { Code = 0 };
HttpPostedFile file = HttpContext.Current.Request.Files[0];
if (file == null)
{
apiResult.Code = -1;
apiResult.Msg = "未获取到图片";
return Json(apiResult);
}
string fileName = file.FileName.ToLower();
string extension = System.IO.Path.GetExtension(fileName).ToLower();
if (!".jpg.jpeg.png.gif.bmp".Contains(extension))
{
apiResult.Code = -1;
apiResult.Msg = "只能上传图片格式为(.jpg.jpeg.png.gif.bmp)";
return Json(apiResult);
}
int maxFileLength = Convert.ToInt32(1024 * 0.5);
if (file.ContentLength / 1024 > maxFileLength)
{
apiResult.Code = -1;
apiResult.Msg = "上传图片不能超过" + maxFileLength + "KB";
return Json(apiResult);
}
string foldName = Misc.GetRequstValue("FoldName");//这里获取的参数是否有定义存储路径
if (string.IsNullOrWhiteSpace(foldName))
{
foldName = FoldName;
}
string savePath = "/Resource/" + foldName + "/" + showData + "/";
string newfilename = Misc.GetRandom(10) + extension;
string fileFullPath = savePath + newfilename;
string biaozhunImgPath = HttpContext.Current.Server.MapPath(savePath);
if (!Directory.Exists(biaozhunImgPath))
{
Directory.CreateDirectory(biaozhunImgPath);
}
file.SaveAs(biaozhunImgPath + newfilename);
apiResult.Data = new
{
newName = fileFullPath,
oldName = fileName,
ImgUrl = Misc.GetDevOnlinePath() + fileFullPath //图片路径直接供前端展示
};
return Json(apiResult);
}
public class ApiResultMsg
{
///
/// 0:表示成功 -1:错误
///
[JsonProperty("code")]
public int Code { get; set; }
///
/// 返回信息 返回信息
///
[JsonProperty("msg")]
public string Msg { get; set; }
///
/// 返回数据
///
[JsonProperty("data")]
public object Data { get; set; }
///
/// 返回页面
///
[JsonProperty("back_url")]
public string BackURL { get; set; }
}
文件上传帮助类:
using System.Data;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Xml.Serialization;
using System.Xml;
using System.Text;
using System.Collections.Generic;
namespace JDK.CommonSys.Common
{
public partial class Misc
{
public static string ConvertToShortDateTime(object date, string format)
{
string newValue = "";
try
{
if (date != null)
newValue = Convert.ToDateTime(date).ToString(format);
}
catch
{
}
return newValue;
}
public static void WriteToFile(string strPath, ref byte[] Buffer)
{
// Create a file
FileStream newFile = new FileStream(strPath, FileMode.Create);
// Write data to the file
newFile.Write(Buffer, 0, Buffer.Length);
// Close file
newFile.Close();
}
public static string NewGUID()
{
string newGUID;
newGUID = Guid.NewGuid().ToString();
return newGUID;
}
///
/// 获取Form或者Query值
///
///
///
public static string GetRequstValue(string param)
{
string value = string.Empty;
try
{
value = HttpContext.Current.Request[param].ToString();
}
catch
{
}
return value;
}
public static string ClearFilename(object filename)
{
string file = "";
if (filename != null)
{
file = Convert.ToString(filename);
file = file.Replace("&", "");
file = file.Replace("|", "");
file = file.Replace("'", "");
file = file.Replace("\"", "");
file = file.Replace("%", "");
file = file.Replace("?", "");
file = file.Replace("@", "");
file = file.Replace("/", "");
file = file.Replace(":", "");
file = file.Replace(".", "");
file = file.Replace("-", "");
file = file.Replace("*", "");
file = file.Replace("\\", "");
file = file.Replace(" ", "_");
file = file.Replace("#", "");
}
return file;
}
public static string MaxCharacters(string text, int characters)
{
string value = text;
if (value.Length > characters)
value = value.Substring(0, characters);
return value;
}
///
/// Upload file
///
/// Upload Control
/// Relative path to save file to, with trailing /
/// exensions allowed, lowercase (.jpg .gif)
/// Filename is returned, without the path
public static string UploadFile(FileUpload fileUploadControl, string uploadPath, string allowedExtensions)
{
string ShortData = Misc.ConvertToShortDateTime(System.DateTime.Now, "yyyy-MM-dd");
string savePath = HttpContext.Current.Server.MapPath(uploadPath + "//" + ShortData + "//");
string newFileName = "";
if (fileUploadControl.HasFile)
{
string fileName = HttpContext.Current.Server.HtmlEncode(fileUploadControl.FileName);
string extension = System.IO.Path.GetExtension(fileName);
if (allowedExtensions.Contains(extension.ToLower()))
{
newFileName = Misc.MaxCharacters(System.Guid.NewGuid().ToString(), 5) + "-" + Misc.MaxCharacters(fileUploadControl.FileName.Replace(extension, ""), 20) + extension;
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
savePath += newFileName;
fileUploadControl.SaveAs(savePath);
}
else
{
newFileName = "";
}
}
return ShortData + "/" + newFileName;
}
///
/// Upload file
///
/// FlieBase
/// Upload Control
/// Relative path to save file to, with trailing /
/// exensions allowed, lowercase (.jpg .gif)
/// Filename is returned, without the path
public static string UploadFile(HttpPostedFileBase FlieBase, string uploadPath, string allowedExtensions)
{
string ShortData = Misc.ConvertToShortDateTime(System.DateTime.Now, "yyyy-MM-dd");
string savePath = HttpContext.Current.Server.MapPath(uploadPath + "//" + ShortData + "//");
string newFileName = "";
if (FlieBase != null)
{
string fileName = HttpContext.Current.Server.HtmlEncode(FlieBase.FileName);
string extension = System.IO.Path.GetExtension(fileName);
if (allowedExtensions.Contains(extension.ToLower()))
{
newFileName = Misc.MaxCharacters(System.Guid.NewGuid().ToString(), 5) + "-" + Misc.MaxCharacters(FlieBase.FileName.Replace(extension, ""), 20) + extension;
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
savePath += newFileName;
FlieBase.SaveAs(savePath);
}
else
{
newFileName = "";
}
}
return ShortData + "/" + newFileName;
}
///
/// 获取Length位随机数(不重复)
///
///
///
public static string GetRandom(int Length)
{
var result = new StringBuilder();
for (var i = 0; i < Length; i++)
{
var r = new Random(Guid.NewGuid().GetHashCode());
result.Append(r.Next(0, 10));
}
return result.ToString();
}
///
/// 随机排序
///
///
///
///
///
public static T[] ShuffleCopy(IEnumerable data, Random r)
{
var arr = data.ToArray();
for (var i = arr.Length - 1; i > 0; --i)
{
int randomIndex = r.Next(i + 1);
T temp = arr[i];
arr[i] = arr[randomIndex];
arr[randomIndex] = temp;
}
return arr;
}
///
/// 获取开发线上前缀URL地址
///
///
public static string GetDevOnlinePath()
{
return HttpContext.Current.Request.Url.Host == "localhost"
? HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority
: ConfigHelper.GetConfigString("Member_URL");//KEY
}
}
}
注意要点:
客户端如果是form表单的提交方式需要在表单里添加"enctype"属性如下:
如果是ajax或者axios的方式提交
data参数部分可以使用FormData对象,也要注意记得附带请求类型Content-Type : "multipart/form-data",这样服务端才能通过Request.Files[0] 获取到上传的文件,另外通过FormData的方式也可以实现文件批量上传
import axios from 'axios' //这里引用axios组件,类似与ajax
Vue.prototype.$ajax = axios //挂载到vue全局变量中
export default{
data:function(){
return{
param: null,
}
},
mounted() {},
created() {},
methods: {
handleUpload(file){
let config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
this.param = this.param || new FormData();
this.param.append("file", file.raw, file.name);
this.$ajax.post("API/UploadImg_SaveFile",this.param,config).then(res =>{
})
}
}
}