上传图片

 

 

 

view

引用js    ajaxfileupload.js

 

  1 <style type="text/css">
  2     .float {
  3         float: left;
  4         width: 200;
  5         height: 200;
  6         overflow: hidden;
  7         border: 1px solid #CCCCCC;
  8         border-radius: 10px;
  9         padding: 5px;
 10         margin: 5px;
 11     }
 12 
 13     img {
 14         position: relative;
 15     }
 16 
 17     .result {
 18         width: 200px;
 19         height: 200px;
 20         text-align: center;
 21         box-sizing: border-box;
 22     }
 23 </style>
 24 <script>
 25     function upload_cover(obj) {
 26         //回传后缀
 27         var filePath = $("input[name='file']").val();
 28         var extStart = filePath.lastIndexOf(".");
 29         var ext = filePath.substring(extStart, filePath.length).toUpperCase();
 30         ajax_upload(obj.id, function (data) { //function(data)是上传图片的成功后的回调方法
 31             var isrc = data.relatPath.replace(/\/\//g, '/'); //获取的图片的绝对路径
 32            
 33         }, ext);
 34     }
 35 
 36     //具体的上传图片方法
 37     function ajax_upload(feid, callback, ext) {
 38         if (image_check(feid)) {
 39             $.ajaxFileUpload({
 40                 url: "/文件夹/控制器/UploadImage",
 41                 secureuri: false,
 42                 fileElementId: feid,
 43                 dataType: 'json',
 44                 data: { fileType: ext },//增加推送的属性
 45                 type: 'post',
 46                 async: false,
 47                 success:
 48                 function (data) {
 49                     result = '<div style="display:none" id="imgdiv" class="result" ><span>*</span><img src="' + data.imagePath + '" alt=""/></div>';
 50                     div = document.createElement('div');
 51                     div.innerHTML = result;
 52                     div['className'] = 'float';
 53                     document.getElementsByTagName('body')[0].appendChild(div);    //插入dom树
 54                     var img = div.getElementsByTagName('img')[0];
 55                     img.onload = function () {
 56                         var nowHeight = ReSizePic(this); //设置图片大小
 57                         this.parentNode.style.display = 'block';
 58                         var oParent = this.parentNode;
 59                         if (nowHeight) {
 60                             oParent.style.paddingTop = (oParent.offsetHeight - nowHeight) / 2 + 'px';
 61                         }
 62                     }
 63                 },
 64                 error:
 65                 function (data) {
 66                     // alert(data);
 67                 }
 68             });
 69         }
 70     };
 71     function image_check(feid) { //自己添加的文件后缀名的验证
 72         var img = document.getElementById(feid);
 73         return /.(jpg|png|gif|bmp)$/.test(img.value) ? true : (function () {
 74             alert('图片格式仅支持jpg、png、gif、bmp格式,且区分大小写。');
 75             return false;
 76         })();
 77     }
 78 
 79 
 80 function ReSizePic(ThisPic) {
 81     var RePicWidth = 200; //这里修改为您想显示的宽度值
 82 
 83     var TrueWidth = ThisPic.width; //图片实际宽度
 84     var TrueHeight = ThisPic.height; //图片实际高度
 85 
 86     if(TrueWidth>TrueHeight){
 87         //宽大于高
 88         var reWidth = RePicWidth;
 89         ThisPic.width = reWidth;
 90         //垂直居中
 91         var nowHeight = TrueHeight * (reWidth/TrueWidth);
 92         return nowHeight;  //将图片修改后的高度返回,供垂直居中用
 93     }else{
 94         //宽小于高
 95         var reHeight = RePicWidth;
 96         ThisPic.height = reHeight;
 97     }
 98 }
 99 </script>
100 <body ng-controller="Aaa">
101     <div class="container">
102         @*<div>
103             <label>附件:</label>
104             <input type="file" id="file" multiple style="display:inline-block;" />
105         </div>*@
106         <div >
107             <label>请选择一个图像文件:</label>
108             <input type="file" id="file_input" multiple style="display:inline-block;display:none"  /> <!--用input标签并选择type=file,记得带上multiple,不然就只能单选图片了-->
109             <input type="file" id="oInput" name="file" onchange="upload_cover(this)" style="display:inline-block" /> 
110             <button>提交</button>
111         </div>
112     </div>
113 </body>

Controller 

 1 #region  图片上传
 2         [HttpPost]
 3         public ActionResult UploadImage(HttpPostedFileBase file)
 4         {
 5            6             //获取图片后缀
 7             string fileType = Request.Form["fileType"];
 8             // 时间
 9             string now = DateTime.Now.ToString("yyyyMMddHHmmssffff");
10             // 文件相对路径
11             string relativePath = "/Upload/" + now + fileType;
12             //文件存放的文件路径
13             string folder = HttpContext.Server.MapPath("/Upload/");
14 
15             // 保存文件
16             string localFilePath = Path.Combine(folder, now + fileType);
17             file.SaveAs(localFilePath);
18             //Session["path"] = relativePath;
19             //切出相对路径
20             JsonResult json = new JsonResult();
21             json.ContentType = "text/html";
22             json.Data = new { imagePath = relativePath, success = true };
23 
24             //OapiFileUploadSingleRequest request = new OapiFileUploadSingleRequest();
25             //request.FileSize=(1000L);
26             //request.AgentId=("312710724");
27             //DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/file/upload/single?" + WebUtils.BuildQuery(request.GetParameters()));
28             //// 必须重新new一个请求
29             //request = new OapiFileUploadSingleRequest();
30             //request.File=(new FileItem(localFilePath));
31             //OapiFileUploadSingleResponse response = client.Execute(request, accessToken);
32 
33            // OapiMediaUploadResponse imgmedia = dingApp.UploadFile("image", localFilePath);
34 
35             return json;
36             //return Content(filePath);
37         }
38         #endregion

 

 

webAPI

 1 <script>
 2     
 3  function upload_cover(obj) {
 4         //回传后缀
 5         var filePath = $("input[name='oInput']").val();
 6         var extStart = filePath.lastIndexOf(".");
 7         var ext = filePath.substring(extStart, filePath.length).toUpperCase();
 8         ajax_upload(obj.id, function (data) { //function(data)是上传图片的成功后的回调方法
 9             var isrc = data.relatPath.replace(/\/\//g, '/'); //获取的图片的绝对路径
10 
11         }, ext);
12     }
13 
14     //具体的上传图片方法
15     function ajax_upload(feid, callback, ext) {
16         if (image_check(feid)) {
17          var formData = new FormData($( "#uploadForm" )[0]);
18             $.ajax({
19                 type:"post",
20                 url:"http://test.test.com/api/FAAPI/UploadFile",
21                 data:formData,
22                 async: false,
23                 cache: false,
24                 contentType: false,
25                 processData: false,
26                 success:function(data){
27                     28                     var div="<div style='width:88px;height:80px;overflow:hidden;border-radius:5px;display:inline-block;border:1px solid;'><img src='http://test.test.com/h5/images/button_pm_close.png' onclick='imgdel(this)' style='folat:left'/><div style='width:85px;height:80x;text-align:center;' class='result'><img src='http://test.test.com/upload/"+data+"'style=' position: relative;'/></div></div>"
29                      var imgd = document.getElementById('imgbody')
30                      $("#imgbody").append(div);         
31                     var img = imgd.getElementsByTagName('img')[0];
32                     img.onload = function () {
33                         var nowHeight = ReSizePic(this); //设置图片大小
34                        // this.parentNode.style.display = 'block';
35                         var oParent = this.parentNode;
36                         if (nowHeight) {
37                             oParent.style.paddingTop = (oParent.offsetHeight - nowHeight) / 2 + 'px';
38                         }
39                     }
40                 }
41             })
42         }
43     };
44     function imgdel(obj){
45          obj.parentNode.parentNode.removeChild(obj.parentNode);
46     }
47     function image_check(feid) { //自己添加的文件后缀名的验证
48         var img = document.getElementById(feid);
49         return /.(jpg|png|gif|bmp)$/.test(img.value) ? true : (function () {
50             alert('图片格式仅支持jpg、png、gif、bmp格式,且区分大小写。');
51             return false;
52         })();
53     }
54 
55 
56     function ReSizePic(ThisPic) {
57         var RePicWidth = 80; //这里修改为您想显示的宽度值
58 
59         var TrueWidth = ThisPic.width; //图片实际宽度
60         var TrueHeight = ThisPic.height; //图片实际高度
61 
62         if (TrueWidth > TrueHeight) {
63             //宽大于高
64             var reWidth = RePicWidth;
65             ThisPic.width = reWidth;
66             //垂直居中
67             var nowHeight = TrueHeight * (reWidth / TrueWidth);
68             return nowHeight;  //将图片修改后的高度返回,供垂直居中用
69         } else {
70             //宽小于高
71             var reHeight = RePicWidth;
72             ThisPic.height = reHeight;
73         }
74     }
75     
76 </script>
77 
78 <div>
79     <label>请选择一个图像文件:</label>
80     <form id= "uploadForm">
81           <input type="file" id="oInput"  name="oInput" onchange="upload_cover(this)" style="display:inline-block" />
82     </form>
83     <div id="imgbody" style="display:inline-block">
84      </div>
85 </div>

 

 

 1 /// <summary>
 2         /// 上传文件
 3         /// </summary>
 4         [HttpPost]
 5         public string UploadFile()
 6         {
 7             string result = string.Empty;
 8             try
 9             {
10                 string uploadPath = HttpContext.Current.Server.MapPath("~/Upload/");
11                 HttpRequest request = System.Web.HttpContext.Current.Request;
12                 HttpFileCollection fileCollection = request.Files;
13                 // 判断是否有文件
14                 if (fileCollection.Count > 0)
15                 {
16                     log.Error("start");
17                     // 获取文件
18                     HttpPostedFile httpPostedFile = fileCollection[0];
19                     string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件扩展名
20                     string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExtension;// 名称//Guid.NewGuid().ToString() 
21                     string filePath = uploadPath + httpPostedFile.FileName;// 上传路径
22                     // 如果目录不存在则要先创建
23                     if (!Directory.Exists(uploadPath))
24                     {
25                         Directory.CreateDirectory(uploadPath);
26                     }
27                     // 保存新的文件
28                     while (File.Exists(filePath))
29                     {
30                         fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExtension;
31                         filePath = uploadPath + fileName;
32                     }
33                     httpPostedFile.SaveAs(filePath);
34                     result = "http://fac.pxtsc.com/upload/"+fileName;// filePath;
35               
36                   
37                 }
38             }
39             catch (Exception ex)
40             {
41                 result = "上传失败";
42               
43             }
44             return result;
45         }
46 
47         /// <summary>
48         /// DownloadFile 下载文件
49         /// </summary>
50         [HttpGet]
51         public void DownloadFile()
52         {
53             var request = HttpContext.Current.Request;
54             NameValueCollection nvCollection = request.Params;
55             string fileName = nvCollection.GetValues("fileName")[0];
56             string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Upload/"), fileName);
57             if (File.Exists(filePath))
58             {
59                 HttpResponse response = HttpContext.Current.Response;
60                 response.Clear();
61                 response.ClearHeaders();
62                 response.ClearContent();
63                 response.Buffer = true;
64                 response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName));
65                 response.Charset = "GB2312";
66                 response.ContentEncoding = Encoding.GetEncoding("GB2312");
67                 response.ContentType = MimeMapping.GetMimeMapping(fileName);
68                 response.WriteFile(filePath);
69                 response.Flush();
70                 response.Close();
71             }
72         }
posted @ 2020-01-07 10:20  江小白ra  阅读(232)  评论(0编辑  收藏  举报