Back-end code:
/// <summary> /// 图片上传,上传路径: "/Uploads/Images/" + folder + "/" + saveName /// </summary> /// <param name="fileData"></param> /// <returns></returns> [HttpPost] public JsonResult UploadImage([FromServices]IWebHostEnvironment environment,string folder) { try { var files = Request.Form.Files; //string contentRootPath = environment.ContentRootPath;//项目所在路径 string webRootPath = environment.WebRootPath;wwwroot folder path where// string filePath = webRootPath + "/Uploads/Images/" + folder + "/"; string fullPath = ""; string uploadPath = ""; foreach (var formFile in files) { string fileName = Path.GetFileName(formFile.FileName);// 原始文件名称 string fileExtension = Path.GetExtension(fileName).ToLower(); // 文件扩展名 string saveName = DateTime.Now.ToString("yyyyMMddhhmmssffff") + fileExtension; // 保存文件名称 int filesize = int.Parse(formFile.Length.ToString()) / 1024;//图片大小(KB) if (filesize > 5120 || filesize <= 2 || (fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".gif")) { return Json(new { Success = false, Message = "upload failed! \ r Please upload jpg / png / gif format images, the file size should not exceed 5MB nor less than 2K " }); } fullPath = Path.Combine (filePath, SAVENAME); IF (! Directory.Exists (filePath)) { Directory. CreateDirectory (filePath); } the using ( var Stream = new new the FileStream (fullPath, FileMode.CreateNew)) { formFile.CopyTo (Stream); } uploadPath = " / the Uploads / Images / " + folder + "/" + saveName; } return Json(new { Success = true, FilePath = uploadPath }); } catch (Exception e) { NLogHelper.WriteDebug("图片上传方法异常:"+ e.Message.ToString()); return Json(new { Success = false, Message = e.Message.ToString() }); } }
Front-end code:
<tr> <th class="formTitle">导航图片</th> <td class="formValue" colspan="3"> <input type="file" id="picture_upload" name="picture_upload" value='导航图片' /> </td> </tr> <link href="~/scripts/plugins/uploadify/uploadify.css" rel="stylesheet" /> <script src="~/scripts/plugins/uploadify/jquery.uploadify.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#picture_upload').uploadify({ uploader: '/Uploads/UploadImage?folder=ArticleCategory', swf: '/scripts/plugins/uploadify/uploadify.swf', buttonText: "请选择上传图片", height: 30, width: 120 , // 'FileExt': '.. * .Jpg; * GIF, PNG *', // allow file format for upload .jpg *, * GIF, PNG *.. // 'filedesc': 'Web Image files (.JPG, .GIF, .PNG) ', // filter out except * .jpg, * gif, * png file.. // ' QueueID ':' fileQueue ', ' the sizeLimit ' : ' 5.12 million ' , / / maximum allowable file size 5M // 'Auto': false, // need to submit an application manual ' Multi ' : false , // once only allowed to upload a picture ' onUploadSuccess ' :function(File, Data, Response) { var obj = jQuery.parseJSON (Data); // the return of the object obj Json sequence into IF (obj.success) { $ ( ' #PictureUrl ' ) .val (obj.filePath) ; } the else Alert (obj.Message); } }); }); </ Script >