最基本图片上传及文件上传(完整版)
不多说直接上代码
html
<input type="file" class="file" name="User_Img1" id="User_Img3" accept="image/jpeg,image/gif,image/png,image/bmp">
js
<script src="Content/jquery-1.10.2.js"></script> <script> $(function () { $("#User_Img3").on("change", function () { var form = new FormData(); //form.append("author", "hooyes"); // 可以增加表单数据 var data = $(this)[0].files[0]; form.append("file", data); //var data = $(this)[0].files[0]; //var form = new FormData(data); $.ajax({ url: '/home/Upload', type: 'post', //发送到服务器端的数据的格式,取消默认编码格式 contentType: false, dataType: 'json', data: form, //因为是图片,不要对其作序列化处理 processData: false, success: function (data) { if (data) { alert(data); } }, err: function (jqHXR) { console.log(jqXHR.status); } }); }); }) </script>
c#MVC
public ActionResult Upload() { HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; if (files.Count == 0) return Json("Faild", JsonRequestBehavior.AllowGet); MD5 md5Hasher = new MD5CryptoServiceProvider(); /*计算指定Stream对象的哈希值*/ byte[] arrbytHashValue = md5Hasher.ComputeHash(files[0].InputStream); /*由以连字符分隔的十六进制对构成的String,其中每一对表示value中对应的元素;例如“F-2C-4A”*/ string strHashData = System.BitConverter.ToString(arrbytHashValue).Replace("-", ""); string FileEextension = Path.GetExtension(files[0].FileName); string uploadDate = DateTime.Now.ToString("yyyyMMdd"); string virtualPath = string.Format("/Upload/{0}/{1}{2}", uploadDate, strHashData, FileEextension); string fullFileName = Server.MapPath(virtualPath); //创建文件夹,保存文件 string path = Path.GetDirectoryName(fullFileName); Directory.CreateDirectory(path); if (!System.IO.File.Exists(fullFileName)) { files[0].SaveAs(fullFileName); } string fileName = files[0].FileName.Substring(files[0].FileName.LastIndexOf("\\") + 1, files[0].FileName.Length - files[0].FileName.LastIndexOf("\\") - 1); string fileSize = GetFileSize(files[0].ContentLength); return Json(new { FileName = fileName, FilePath = virtualPath, FileSize = fileSize }, "text/html", JsonRequestBehavior.AllowGet); }
加入js图片验证:
//上传图片 function uploadImg(self) { var file = self.files[0]; if (file == undefined || file == "") { layer.open({ content: '请选择上传的图片' , skin: 'msg' , time: 2 //2秒后自动关闭 }); return; } var filename = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();//获取上传文件的类型 if (filename != "jpg" && filename != "png" && filename != "jpeg") { layer.open({ content: "只能上传JPG/PNG/JPEG格式的图片,您上传的格式为:" + filename , skin: 'msg' , time: 2 //2秒后自动关闭 }); return; } if (file.size > 1024 * 1024 * 5) { layer.open({ content: '上传的图片不能超过5MB' , skin: 'msg' , time: 2 //2秒后自动关闭 }); return; } var form = new FormData(); form.append('upfile', file); form.append('type', filename); $.ajax({ url: '/Home/UpLoadImg', type: 'POST', data: form, async: true, cache: false, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType }).done(function (data) { layer.open({ content: data.Message , skin: 'msg' , time: 2 //2秒后自动关闭 }); if (data.ResultCode === 1000) { } }).fail(function () { layer.open({ content: '图片错误,请重新选择!' , skin: 'msg' , time: 2 //2秒后自动关闭 }); }); }
后台:
/// <summary> /// 图片上传 /// </summary> /// <returns></returns> [HttpPost] public ActionResult UploadImage() { //Qiniufun qiniufun = new Qiniufun();//七牛实例化 //qiniufun.init();//七牛初始化 var blob = Request.Form["imagefile"]; if (blob == null) { blob = Request.Form["imagefile2"]; } var type = Request.Form["type"]; var filename = string.Format("{0:yyyyMMddHHmmssfffffff}", DateTime.Now); string path = HttpContext.Server.MapPath("/images/Uploads"); string filePath = Path.Combine(path, Path.GetFileName(filename)); //根据需要创建文件夹 Tools.CreateFolderIfNeeded(path); //压缩后的文件名称 string newFileName = string.Format("{0:yyyyMMddHHmmssfffffff}", DateTime.Now); try { byte[] arr = Convert.FromBase64String(blob.ToString()); MemoryStream ms = new MemoryStream(arr); Bitmap bmp = new Bitmap(ms); if (type.ToLower() == "jpeg" || type == "jpg") { filePath += ".jpg"; bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg); //保存为.jpg格式 ms.Close(); } else if (type.ToLower() == "png") { filePath += ".png"; bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png); //保存为.jpg格式 ms.Close(); } else if (type.ToLower() == "gif") { filePath += ".gif"; bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Gif); //保存为.jpg格式 ms.Close(); } QiniuUpload.UpLoadImg(filename + "." + type.ToLower(), filePath); var name = QiniuUpload.outlink + filename + "." + type.ToLower();//七牛地址 //qiniufun.PutFile(qiniufun.qnSpace, qiniufun.fullname("/" + filename), filePath);//上传到七牛初 //var name = qiniufun.outlink + qiniufun.fullname("/" + filename);//七牛地址 return Json("Success|" + name, JsonRequestBehavior.AllowGet); //返回诸如 http://7xlcvw.com2.z0.glb.qiniucdn.com/CiviBank/201601081019336945309.jpg } catch (Exception e) { return Json("error:" + e.Message, JsonRequestBehavior.AllowGet); } }