1.前台 首先引用dropzone.css
$("#dropz").dropzone({
url: "/API/Home/FileUpload/",
maxFiles: 10,
maxFilesize: 50,
acceptedFiles: ".ppt,.pptx,.pdf,jpg,png,gif",
autoProcessQueue: false,
paramName: "file",
dictDefaultMessage: "拖入需要上传的文件",
addRemoveLinks: true,
autoProcessQueue: true,
init: function () {
this.on('success', function (files, response) {
fileUrl = response.Url;
flag = true;
});
this.on("removedfile", function (files, response) {
console.log("File " + files.name + "removed");
});
}
});
2.后台
[HttpPost]
public Result FileUpload()
{
//接收表单传递过来的文件,需要限定上传的文件格式:".JPG", ".JPEG", ".GIF", ".PNG", ".BMP"
var file = HttpContext.Current.Request.Files["file"];
//首先判断表单中的员工id和证书记录是否为空,为空则限制客户从客户端上传文件,因为即使上传成功也对应不到记录
Result lap = new Result();
//检查文件是否被预览选中,判断方式:通过判断文件名是否为空或者空字符串
if (!string.IsNullOrWhiteSpace(file.FileName))
{
//限定上传文件的格式类型
string[] LimitPictureType = {".PPT", ".PPTX", ".PDF", ".JPG", ".PNG", ".GIF" };
//当文件上被选中时,拿到文件的扩展名
string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper();
//此处对文件上传的类型进行限定操作
if (LimitPictureType.Contains(currentPictureExtension))
{
//此处标记文件上传至服务器的唯一新名称
string _newFileName = Guid.NewGuid().ToString();
string _toServerPicturePath = DateTime.Now.Year + "/" + DateTime.Now.Month + "/";
string _dbPicturePath = "Intel/Certifications/" + _toServerPicturePath + _newFileName + currentPictureExtension;
_toServerPicturePath = AppDomain.CurrentDomain.BaseDirectory + "Intel/Certifications/" + _toServerPicturePath;//最终生成的文件名:+_newFileName +currentPictureExtension
//首先判断文件上传至服务的路径是否存在,不存在则创建并执行保存操作,存在则直接保存
if (Directory.Exists(_toServerPicturePath))
{
//最终上传的文件路径全名
_toServerPicturePath = _toServerPicturePath + _newFileName + currentPictureExtension;
}
else
{//不存在此路径,则创建后执行保存操作
Directory.CreateDirectory(_toServerPicturePath);
_toServerPicturePath = _toServerPicturePath + _newFileName + currentPictureExtension;
}
//执行保存文件,并插入数据库操作
file.SaveAs(HttpContext.Current.Server.MapPath("~/" + _dbPicturePath));
执行数据库相关操作,没有异常则代码继续执行,否则跳出
//bflag = true;
lap.Url = _dbPicturePath;
lap.Message = "1";
lap.Code = "200";
return lap;
}
else
{
lap.Message = "文件上传操作失败,请选择扩展名为:.ppt,.pptx,.pdf,jpg,png,gif 等类型文件。";
}
}
else
{
lap.Message = "文件上传操作失败,请检查记录是否被选中!";
}
ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
log.Info("UpdatePageView:" + System.DateTime.Now.ToString() + lap.Message);
return lap;
}