JavaScript实现单张图片上传功能

前台jsp代码

  1 <%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=utf-8"%>
  2 <!DOCTYPE html>
  3 <html>
  4 <head>
  5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6     <meta http-equiv=Content-Type content="text/html; charset=utf-8" />
  7     <title>单张图片上传</title>
  8     <link rel="stylesheet" type="text/css" href="/css/upload/uploadImg.css">
  9     <script type="text/javascript" src="/js/jquery-2.0.0.min.js"></script>
 10     <script type="text/javascript" src="/js/layer/layer.js"></script>
 11     <style type="text/css">
 12     </style>
 13 </head>
 14 <body>
 15     <div style="height: 500px;">
 16         <div class="img-box">
 17             <img src="" id="yushow"/>
 18             <button class="btn-uploading" onclick="uploadBtn();"><i class="icon-uploading"></i>上传图片</button>
 19             <a class="shan" onclick="deleteImg();"><img src="/images/upload/shanI.gif"></a>
 20         </div>
 21         <input type="file" name="file" style="display:none;" onchange="previewImg(this);" id="upload" accept="image/*"/>
 22     </div>
 23 </body>
 24 <script type="text/javascript">
 25 
 26 function uploadBtn(){
 27     $("#upload").click();
 28 }
 29 
 30 //图片预览
 31 function previewImg(imgFile){
 32     console.log(imgFile);//这里打印出是整个input标签
 33     var extension = imgFile.value.substring(imgFile.value.lastIndexOf("."),imgFile.value.length);//扩展名
 34     extension = extension.toLowerCase();//把文件扩展名转换为小写
 35     if ((extension!='.jpg')&&(extension!='.gif')&&(extension!='.jpeg')&&(extension!='.png')&&(extension!='.bmp')){
 36         layer.msg("对不起,系统仅支持标准格式的照片,请您调整格式后重新上传,谢谢 !");
 37         $(".btn-uploading").focus();//将焦点定位在文件上传的按钮上,可以直接按确定键再次触发
 38     }else{
 39         var path;//预览地址
 40         if(document.all){//IE
 41             imgFile.select();
 42                 path = document.selection.createRange().text;
 43         }else{//火狐,谷歌
 44             path = window.URL.createObjectURL(imgFile.files[0]);
 45         }
 46         $("#yushow").attr("src",path);//设置预览地址
 47         uploadImg(imgFile);
 48     }
 49 }
 50 
 51 //开始上传
 52 function uploadImg(imgFile){
 53     //获取图片文件
 54     var file = imgFile.files[0];//文件对象
 55     var name = file.name;//图片名
 56     //var size = file.size;//图片大小
 57     //var type = file.type;//文件类型
 58     
 59     //检测浏览器对FileReader的支持
 60     if(window.FileReader) {
 61         var reader = new FileReader();
 62         reader.onload = function(){//异步方法,文件读取成功完成时触发
 63             var dataImg = reader.result;//文件一旦开始读取,无论成功或失败,实例的 result 属性都会被填充。如果读取失败,则 result 的值为 null ,否则即是读取的结果
 64             syncUpload(name,dataImg);
 65         };
 66         reader.readAsDataURL(file);//将文件读取为 DataURL
 67     }else {
 68         layer.msg("浏览器不支持H5的FileReader!");
 69     }
 70 }
 71 
 72 function syncUpload(name,dataImg){
 73     var imgFile = dataImg.replace(/\+/g,"#wb#");//将所有“+”号替换为“#wb#”
 74     imgFile = imgFile.substring(imgFile.indexOf(",")+1);//截取只保留图片的base64部分,去掉了data:image/jpeg;base64,这段内容
 75     imgFile = encodeURIComponent(imgFile);//把字符串作为 URI 组件进行编码。后台容器会自动解码一次
 76     name = encodeURIComponent(encodeURIComponent(name));//这里对中文参数进行了两次URI编码,后台容器自动解码了一次,获取到参数后还需要解码一次才能得到正确的参数内容
 77     var mydata = "method=uploadImg&imgFile="+imgFile+"&imgName="+name;
 78     $.ajax({
 79           url: "/UploadServlet",
 80           data: mydata,
 81           type: "post",
 82           dataType: "json",
 83           success: function(data){
 84                   if(data.state == 'ok'){
 85                       document.getElementById("upload").value = "";//重置文件域
 86                       layer.msg(data.msg);
 87                 }else if(data.state == 'error'){
 88                     layer.msg(data.msg);
 89                 }
 90           }
 91     });
 92 }
 93 
 94 //删除图片
 95 function deleteImg(){
 96     $.ajax({
 97           url: "/UploadServlet",
 98           data: "method=deleteImg",
 99           type:"post",
100           dataType: "json",
101           success: function(data){
102                   if(data.state == 'ok'){
103                       layer.msg(data.msg);
104                 }else if(data.state == 'error'){
105                     layer.msg(data.msg);
106                 }
107           }
108     });
109 }
110 </script>
111 </html>

后台Servlet代码

  1 package com.demo.servlet;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.ByteArrayInputStream;
  5 import java.io.File;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.io.InputStream;
  9 import java.net.URLDecoder;
 10 
 11 import javax.servlet.ServletException;
 12 import javax.servlet.annotation.WebServlet;
 13 import javax.servlet.http.HttpServlet;
 14 import javax.servlet.http.HttpServletRequest;
 15 import javax.servlet.http.HttpServletResponse;
 16 
 17 import net.sf.json.JSONObject;
 18 import sun.misc.BASE64Decoder;
 19 
 20 /**
 21  * 文件上传Servlet
 22  */
 23 @WebServlet("/UploadServlet")
 24 public class UploadServlet extends HttpServlet {
 25     private static final long serialVersionUID = 1L;
 26     public UploadServlet() {
 27         super();
 28     }
 29     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 30         this.doPost(request, response);
 31     }
 32     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 33         try {
 34             String method = request.getParameter("method");
 35             if (method != null) {
 36                 if (method.equals("uploadImg")) {
 37                     this.uploadImg(request,response);
 38                 }else if (method.equals("deleteImg")) {
 39                     this.deleteImg(request, response);
 40                 }
 41             }else {//当不能从request中直接获取到数据的时候需要从流中读取
 42                 try {
 43                     BufferedReader br = request.getReader();
 44                     String line = null;
 45                     StringBuffer sb = new StringBuffer();
 46                     while((line = br.readLine())!=null){
 47                         sb.append(line);
 48                     }
 49                     String params = sb.toString();
 50                     if(params.contains("method")){                
 51                         request.setAttribute("params", params);
 52                         if (params.contains("uploadImg")){                            
 53                             this.uploadImg(request,response);
 54                         } else if (params.contains("deleteImg")){
 55                             this.deleteImg(request, response);
 56                         } 
 57                         return;
 58                     } else {
 59                         response.getWriter().print("missing parameter 'method'!");
 60                     }
 61                 } catch (Exception e) {
 62                     e.printStackTrace();
 63                 } finally {
 64                     try {
 65                         response.getWriter().close();
 66                     } catch (Exception e) {}
 67                 }
 68             }
 69         } catch (Exception e) {
 70             e.printStackTrace();
 71         }
 72     }
 73     /**
 74      * 上传图片
 75      * @param request
 76      * @param response
 77      */
 78     private void uploadImg(HttpServletRequest request,HttpServletResponse response) {
 79         try {
 80             System.out.println("=================《《图片开始上传》》===================");
 81             response.setContentType("text/html;charset=utf-8");
 82             String imgFile = request.getParameter("imgFile");
 83             String imgName = request.getParameter("imgName");
 84             
 85             //request中没获取到参数时的处理
 86             if (imgFile == null  || imgName == null ) {
 87                 String params = (String)request.getAttribute("params");
 88                 if (params != null && imgFile == null && params.indexOf("imgFile=") != -1){
 89                     imgFile = params.substring(params.indexOf("imgFile=") + "imgFile=".length(), params.indexOf("&imgName="));                   
 90                 }else {
 91                     System.out.println("imgFile参数错误");
 92                     response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'imgFile参数错误'}").toString());
 93                     return;
 94                 }
 95                 if (params != null && imgName == null && params.indexOf("imgName=") != -1) {
 96                     imgName = params.substring(params.indexOf("imgName=") + "imgName=".length());
 97                 }else {
 98                     System.out.println("imgName参数错误");
 99                     response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'imgName参数错误'}").toString());
100                     return;
101                 }
102             }
103             //对参数为空进行判断
104             if ("".endsWith(imgFile.trim()) || "".endsWith(imgName.trim())) {
105                 System.out.println("参数为空");
106                 response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'参数为空'}").toString());
107                 return;
108             }
109             
110             imgName = URLDecoder.decode(imgName,"utf-8");//前面进行了两次编码,这里需要用解码器解码一次
111             //String path = "/site/images"+File.separator+imgName;//Linux文件保存路径
112             String path = "F:\\site\\images"+File.separator+imgName;//Windows文件保存路径
113             
114             //File file = new File("/site/images");
115             File file = new File("F:\\site\\images");
116             if(!file.exists() && !file.isDirectory()){//如果文件夹不存在则创建 
117                 System.out.println("文件目录不存在,开始创建");
118                 //file.mkdirs();//生成所有目录
119                 //file.mkdir();//生成最后一层目录
120                 if (!file.mkdirs()) {
121                     System.out.println("文件目录创建失败");
122                     response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'文件目录创建失败'}").toString());
123                     return;
124                 }
125             }
126             
127             FileOutputStream os = new FileOutputStream(path);
128             imgFile = imgFile.replaceAll("#wb#", "+");
129             BASE64Decoder decoder = new BASE64Decoder();
130             byte[] b = decoder.decodeBuffer(imgFile);
131             for(int i=0;i< b.length;++i){
132                 if(b[i]< 0){//调整异常数据
133                     b[i]+=256;
134                 }
135             }
136             InputStream is = new ByteArrayInputStream(b);
137             int len = 0;
138             while((len=is.read(b))!=-1){
139                 os.write(b,0,len);
140             }
141             os.close();
142             is.close();
143             System.out.println("上传成功,文件保存在:"+path);
144             response.getWriter().print(JSONObject.fromObject("{'state':'ok','msg':'上传成功'}").toString());
145         } catch (Exception e) {
146             e.printStackTrace();
147             try {
148                 response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'"+e.getMessage()+"'}").toString());
149             } catch (IOException e1) {
150                 e1.printStackTrace();
151             }
152         }
153         
154     }
155     /**
156      * 删除图片
157      * @param request
158      * @param response
159      */
160     private void deleteImg(HttpServletRequest request,HttpServletResponse response) {
161         try {
162             System.out.println("=================《《图片开始删除》》===================");
163             String path = request.getParameter("path");
164             if (path == null || "".endsWith(path.trim())) {
165                 System.out.println("path参数错误");
166                 response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'path参数错误'}").toString());
167                 return;
168             }
169             //删除文件
170             File file = new File(path);
171             //路径存在并且为文件则进行删除  
172             if (file.exists() && file.isFile()) {  
173                 file.delete();
174                 System.out.println("删除成功,文件路径:"+path);
175                 response.getWriter().print(JSONObject.fromObject("{'state':'ok','msg':'删除成功'}").toString());
176             }
177         } catch (Exception e) {
178             e.printStackTrace();
179             try {
180                 response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'"+e.getMessage()+"'}").toString());
181             } catch (IOException e1) {
182                 e1.printStackTrace();
183             }
184         }
185     }
186 
187 }

css样式表文件

 1 .img-box{
 2     margin:0 auto;
 3     top:50%;
 4     width: 500px;
 5     height: 250px;
 6     position:relative;
 7     background: rgb(249,249,249);
 8     border: 1px solid rgb(197, 190, 190);
 9 }
10 .img-box img{
11     max-width: 100%;
12     max-height: 100%;
13     position: absolute;/*绝对定位*/
14     top:50%;
15     left: 50%;
16     -webkit-transform: translate(-50%,-50%); /*-webkit-是厂商前缀*/
17         -ms-transform: translate(-50%,-50%); /*-ms-是厂商前缀*/
18             transform: translate(-50%,-50%);/*translate是移动属性,两个-50%代表着像原始位置向左、向上各移动50%*/
19 }
20 
21 .btn-uploading{    
22     width: 112px;
23     background-color: #3598db;
24     font-size: 15px;
25     line-height: 38px;
26     color: #fff;
27     position:absolute;
28     top:50%;
29     margin-top:-16px;
30     left: 50%;
31     margin-left: -62px;
32     text-align: center;
33     border-radius: 3px;
34     z-index: 5;
35     cursor: pointer;
36 }
37 .icon-uploading{
38     width: 27px;
39     height: 27px;
40     display: inline-block;
41     background: url(/images/upload//upload.png) no-repeat;
42     position: relative;
43     top:6px;
44 }
45 
46 .shan{
47     position: absolute;
48     right:2px;
49     bottom:5px;
50     width: 9px;
51     height: 12px;
52     cursor:pointer;
53 }
54 
55 button{
56     outline: none;
57     border:0 none;
58     
59 }

页面效果

 

如果想了解多张图片的上传:可参考另一篇博客:JavaScript实现多张图片上传功能

posted @ 2016-12-20 11:26  一线大码  Views(9406)  Comments(0Edit  收藏  举报