上传图片的两种方法(ajaxFileUpload和webuploader)

上传图片的两种方法

  1、ajaxFileUpload上传图片

 

  第一步:先引入jQuery与ajaxFileUpload插件。

  ajaxFileUpload插件下载地址:http://files.cnblogs.com/files/kissdodog/ajaxfileupload_JS_File.rar

<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/ajaxfileupload.js"></script>

  第二步:HTML代码

<body>
    <input type="file" id="file1" name="file" />
    <input type="button" value="上传" />
</body>

  第三步:JS代码

 1 <script type="text/javascript">
 2         $(function () {
 3             $(":button").click(function () {
 4                 if ($("#file1").val().length > 0) {
 5                     ajaxFileUpload();
 6                 }
 7                 else {
 8                     alert("请选择图片");
 9                 }
10             })
11         })
12         function ajaxFileUpload() {
13             $.ajaxFileUpload
14             (
15                 {
16                     url: '/AjaxUpLoader/Upload', //用于文件上传的服务器端请求地址
17                     secureuri: false, //一般设置为false
18                     fileElementId: 'file1', //文件上传空间的id属性  <input type="file" id="file" name="file" />
19                     dataType: 'HTML', //返回值类型 一般设置为json
20                     success: function (data, status)  //服务器成功响应处理函数
21                     {
22                         alert(data);
23                         if (typeof (data.error) != 'undefined') {
24                             if (data.error != '') {
25                                 alert(data.error);
26                             } else {
27                                 alert(data.msg);
28                             }
29                         }
30                     },
31                     error: function (data, status, e)//服务器响应失败处理函数
32                     {
33                         alert(e);
34                     }
35                 }
36             )
37             return false;
38         }
39     </script>

  第四步:后台代码

 1      public ActionResult Upload()
 2         {
 3             NameValueCollection nvc = System.Web.HttpContext.Current.Request.Form;
 4 
 5             HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
 6             string imgPath = "";
 7             if (hfc.Count > 0)
 8             {
 9                 imgPath = "/testUpload" + hfc[0].FileName;
10                 string PhysicalPath = Server.MapPath(imgPath);
11                 hfc[0].SaveAs(PhysicalPath);
12             }
13             //注意要写好后面的第二第三个参数
14             return Json(new { Id = nvc.Get("Id"), name = nvc.Get("name"), imgPath1 = imgPath }, "text/html", JsonRequestBehavior.AllowGet);
15         }

  最后 上传界面及图片展示:

                       

 2、webuploader上传图片

  第一步:先引入所需的插件。

  webuploader官网上下载地址:http://fex.baidu.com/webuploader/

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<link href="~/Content/webuploader.css" rel="stylesheet" />
<script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script src="~/Scripts/webuploader.js"></script>

 

  第二步:HTML代码

<div id="uploadimg">
         <div id="fileList" class="uploader-list"></div>
         <div id="imgPicker">选择图片</div>
</div>

  第三步:JS代码

 1 <script type="text/javascript">
 2     $(function () {
 3         /*init webuploader*/
 4         var $list = $("#thelist");   //这几个初始化全局的百度文档上没说明,好蛋疼。  
 5         var $btn = $("#ctlBtn");   //开始上传  
 6         var thumbnailWidth = 100;   //缩略图高度和宽度 (单位是像素),当宽高度是0~1的时候,是按照百分比计算,具体可以看api文档  
 7         var thumbnailHeight = 100;
 8 
 9         var uploader = WebUploader.create({
10             auto: true, // 选完文件后,是否自动上传   
11             swf: '/Scripts/Uploader.swf', // swf文件路径   
12             server: '@Url.Action("Upload")', // 文件接收服务端   
13             pick: '#imgPicker', // 选择文件的按钮。可选   
14             // 只允许选择图片文件。   
15             accept: {
16                 title: 'Images',
17                 extensions: 'gif,jpg,jpeg,bmp,png',
18                 mimeTypes: 'image/*'
19             }
20         });
21 
22         // 当有文件添加进来的时候
23         uploader.on('fileQueued', function (file) {
24             var $li = $(
25                     '<div id="' + file.id + '" class="file-item thumbnail">' +
26                         '<img>' +
27                         '<div class="info">' + file.name + '</div>' +
28                     '</div>'
29                     ),
30                 $img = $li.find('img');
31 
32             $list.append($li);
33 
34             // 创建缩略图
35             uploader.makeThumb(file, function (error, src) {
36                 if (error) {
37                     $img.replaceWith('<span>不能预览</span>');
38                     return;
39                 }
40 
41                 $img.attr('src', src);
42             }, thumbnailWidth, thumbnailHeight);
43         });
44 
45         // 文件上传过程中创建进度条实时显示。
46         uploader.on('uploadProgress', function (file, percentage) {
47             var $li = $('#' + file.id),
48                 $percent = $li.find('.progress span');
49 
50             // 避免重复创建
51             if (!$percent.length) {
52                 $percent = $('<p class="progress"><span></span></p>')
53                         .appendTo($li)
54                         .find('span');
55             }
56 
57             $percent.css('width', percentage * 100 + '%');
58         });
59 
60         // 文件上传成功,给item添加成功class, 用样式标记上传成功。
61         uploader.on('uploadSuccess', function (file) {
62             $('#' + file.id).addClass('upload-state-done');
63         });
64 
65         // 文件上传失败,现实上传出错。
66         uploader.on('uploadError', function (file) {
67             var $li = $('#' + file.id),
68                 $error = $li.find('div.error');
69 
70             // 避免重复创建
71             if (!$error.length) {
72                 $error = $('<div class="error"></div>').appendTo($li);
73             }
74 
75             $error.text('上传失败');
76         });
77 
78         // 完成上传完了,成功或者失败,先删除进度条。
79         uploader.on('uploadComplete', function (file) {
80             $('#' + file.id).find('.progress').remove();
81         });
82     });
83 </script>

  第四步:控制器代码

 1 [HttpPost]
 2         public ActionResult upload(HttpPostedFileBase file)
 3         {
 4             if (file != null && file.ContentLength > 0)
 5             {
 6                 string folderpath = "/UploadFile/";//上传图片的文件夹
 7                 if (!Directory.Exists(folderpath))
 8                 {
 9                     Directory.CreateDirectory(Server.MapPath(folderpath));
10                 }
11                 string ext1 = Path.GetExtension(file.FileName);
12                 if (ext1 != ".gif" && ext1 != ".jpg" && ext1 != ".jpeg" && ext1 != ".png")
13                 {
14                     return Json(new { statu = 201, msg = "文件格式不正确!" });
15                 }
16                 else
17                 {
18                     string name = DateTime.Now.ToString("yyyyMMddHHmmssff");
19                     string ext = Path.GetExtension(file.FileName);
20                     string downpath = folderpath + name + ext;
21                     string filepath = Server.MapPath(folderpath) + name + ext;
22                     file.SaveAs(filepath);
23                     return Json(new { statu = 200, src = downpath, id = name });
24                 }
25             }
26             else
27             {
28                 return Json(new { statu = 202, msg = "请上传文件!" });
29             }
30 
31         }

  最后 截图:上传界面以及上传的图片

  

 

 

 

 

 

转载于:https://www.cnblogs.com/congcongliu/p/7494218.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值