前端代码:
<div class="ext_tempfileupload" data-fileupload-for="Img"> <span class="btn btn-success"> <span class="glyphicon glyphicon-plus "></span> <span>上传</span> </span> </div>
$.fn.extend({ nyUpload: function (options) { var $this = $(this); let $fileUploadInfoSpan = $("<span></span>"); let $file = $("<input type='file' style='display:none;'/>") .on("change", function () { var formFile = new FormData(); for (var i = 0; i < $(this)[0].files.length; i++) { formFile.append($(this)[0].files[i].name, $(this)[0].files[i]); } if (!formFile) { return; } $fileUploadInfoSpan.text("(准备上传)"); var url ="@Url.Action(nameof(NY.CCP.StatelliteWebApp.Controllers.Webs.InfoController.AjaxMultiFileUploadAsync))"; $.ajax({ url: url, data: formFile , type: "POST", processData: false, // jQuery不要去处理发送的数据 contentType: false, // jQuery不要去设置Content-Type请求头 success: function (data) { $fileUploadInfoSpan.text("(上传成功)"); var dastr = eval(data); var json = eval(dastr.filePathArray); var htmlImg = ""; for (var i = 0; i < json.length; i++) { htmlImg += "<div class="col-4"> <div class="card "> <img class="card-img - top img - thumbnail" src="" + json[i].filePath+"" alt="Card image cap"></div></div>"; } $("#fileImgs").append(htmlImg); }, error: function(){ $fileUploadInfoSpan.text("(获取上传信息失败)"); options.error && options.error("获取上传信息失败"); } }); }); if (options.accept) { $file.attr("accept", options.accept); } if (options.multiple) { $file.attr("multiple", options.multiple); } $this.append($fileUploadInfoSpan).after($file).on("click", function () { $file[0].click(); }); } }); $(function () { // $(".ext_tempfileupload").each(function (index,item) { let $this = $(item); //关联的图片input let $fileIdInput = $("#" + $this.data("forinput-fileid")); let $fileUrlInput = $("#" + $this.data("forinput-fileurl")); let $fileImg = $("#" + $this.data("forimg")); $this.nyUpload({ accept: $this.data("accept"), multiple: $this.data("multiple"), error: function (msg) { }, success: function (data) { if ($fileIdInput) { $fileIdInput.val(data.fileId); } if ($fileUrlInput) { $fileUrlInput.val(data.location); } if ($fileImg) { $fileImg.show().attr("src", data.location); } } }); }); });
后台代码:
private static IHostingEnvironment _hostingEnvironment; /// <summary> /// 对文件上传响应模型 /// </summary> class UploadFileRequest { /// <summary> /// 文件名称 /// </summary> public string FileName { get; set; } /// <summary> /// 文件路径 /// </summary> public string FilePath { get; set; } } public InfoController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; }
/// <summary> /// 多图片上传 /// </summary> /// <param name="formCollection">表单集合值</param> /// <returns>服务器存储的文件信息</returns> public async Task<JsonResult> AjaxMultiFileUploadAsync(IFormCollection formCollection) { var currentDate = DateTime.Now; var webRootPath = _hostingEnvironment.WebRootPath;//>>>相当于HttpContext.Current.Server.MapPath("") var uploadFileRequestList = new List<UploadFileRequest>(); var pathList = new List<string>(); var srcPathList = new List<string>(); try { //FormCollection转化为FormFileCollection var files = (FormFileCollection)formCollection.Files; if (files.Any()) { foreach (var file in files) { var uploadFileRequest = new UploadFileRequest(); var filePath = $"/UploadFile/{currentDate:yyyyMMdd}/"; //创建每日存储文件夹 if (!Directory.Exists(webRootPath + filePath)) { Directory.CreateDirectory(webRootPath + filePath); } //文件后缀 var fileExtension = Path.GetExtension(file.FileName);//获取文件格式,拓展名 //判断文件大小 var fileSize = file.Length; if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b) { continue; } //保存的文件名称(以名称和保存时间命名) var saveName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension; //文件保存 using (var fs = System.IO.File.Create(webRootPath + filePath + saveName)) { file.CopyTo(fs); fs.Flush(); } //完整的文件路径 var completeFilePath = Path.Combine(filePath, saveName); uploadFileRequestList.Add(new UploadFileRequest() { FileName = saveName, FilePath = completeFilePath }); pathList.Add(Utils.CloudFilePathUtils.GetTempImgFilePath(saveName)); srcPathList.Add(webRootPath + filePath + saveName); } } else { return new JsonResult(new { isSuccess = false, resultMsg = "上传失败,未检测上传的文件信息~" }); } } catch (Exception ex) { return new JsonResult(new { isSuccess = false, resultMsg = "文件保存失败,异常信息为:" + ex.Message }); } if (uploadFileRequestList.Any()) {
//CosSDK.TransferBatchUploadObjects(pathList, srcPathList);
//foreach (var item in pathList)
//{
// uploadFileRequestList.Add(new UploadFileRequest()
// {
// FileName = item,
// FilePath = CosSDK.GetObjectUrlWithAuthorization(item, QCloudSDK.Models.Cos.ProtocolType.Https, QCloudSDK.Models.Cos.LineType.Cdn, null)
// });
//}
} return new JsonResult(new { isSuccess = true, returnMsg = "上传成功", filePathArray = uploadFileRequestList }); } else { return new JsonResult(new { isSuccess = false, resultMsg = "网络打瞌睡了,文件保存失败" }); } }