ajaxfileupload上传
//上传图标 function ajaxFileUpload() { $.ajaxFileUpload({ url: "@Url.Action("UploadImgFile", "Upload")", //用于文件上传的服务器端请求地址 secureuri: false, //一般设置为false fileElementId: $("input[name=file_upload]"), //文件上传空间的id属性 dataType: "text", //返回值类型 success: function (data, status) { //服务器成功响应处理函数 var data2 = JSON.parse(data); if (data2.ResultType == "@OperationResultType.Success.ToInt32()") { $("input[name=Icon]").val(data2.ResultMessage); $("label.img-label").text("重传"); } else { showMessage(data2.ResultMessage); } }, error: function (data, status, e) {//服务器响应失败处理函数 showMessage("服务器未响应"); } }); return false; }
/// <summary> /// 浏览上传文件 /// </summary> /// <param name="file_upload">文件</param> /// <returns></returns> public ContentResult UploadImgFile(HttpPostedFileBase file_upload) { OperationResult result; if (file_upload == null) { result = new OperationResult(OperationResultType.Error, "请选择要上传的图片"); } else { var fileExtension = Path.GetExtension(file_upload.FileName).ToLower(); if (!WebConfigInfo.ImageSupportType.Contains(fileExtension)) { result = new OperationResult(OperationResultType.Error, "请上传" + WebConfigInfo.ImageSupportType+"格式的图片"); } else if (file_upload.ContentLength > Convert.ToInt32(WebConfigInfo.IconFileSizeLimit.Remove(WebConfigInfo.IconFileSizeLimit.LastIndexOf(' '))) * 1024) { result = new OperationResult(OperationResultType.Error, "请上传最大不超过" + WebConfigInfo.IconFileSizeLimit+"的图片"); } else { string path = "/upload/" + DateTime.Now.ToString("yyyyMMdd"); string uploadDir = Server.MapPath(WebConfigInfo.VirtualDirectoryName + path); // 如果上传课程文件夹不存在,则创建 if (!Directory.Exists(uploadDir)) Directory.CreateDirectory(uploadDir); string fileUrl = string.Format("{0}/{1}{2}", path, Guid.NewGuid().ToString().Replace("-", string.Empty), fileExtension); file_upload.SaveAs(Server.MapPath(WebConfigInfo.VirtualDirectoryName + fileUrl)); result = new OperationResult(OperationResultType.Success, fileUrl); } } var json = string.Format("{0}\"ResultType\":\"{1}\",\"ResultMessage\":\"{2}\"{3}", "{", result.ResultType.ToInt32(), result.Message, "}"); return Content(json); }