javauploadify上傳圖片並預覽

技術小胖子發表於2017-11-09

前一篇文章可以看到對jquery uploadify的屬性的講解,這裡給出具體的java程式碼實現,程式碼基於servlet,實現了上傳圖片並預覽的效果,不多說,上程式碼


index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<!--引入jquery.js-->
<script src="scripts/jquery-1.10.2.min.js"></script>  
<!--引入uploadify.js-->
<script src="scripts/jquery.uploadify.min.js" type="text/javascript"></script>
<!--引入uploadify.css-->
<link href="css/uploadify.css" rel="stylesheet" type="text/css" />  
<!--引入自己寫的css-->
<link href="css/customer.css" rel="stylesheet" type="text/css" />  
 
<script type="text/javascript">  
        $(function() {  
             $("#upload_org_code").uploadify({
             `auto` :true,
             `buttonClass`:`mybutton`,
             `buttonCursor`:`hand`,
             `buttonText`    `選擇圖片`,
             `fileSizeLimit` `2MB`,
                 `height`        27,
                 `width`         80
                 `fileTypeExts`  `*.jpg;*.jpge;*.gif;*.png`,
                 `fileTypeDesc`  :`請選擇jpg,jpge,jif,png字尾結尾的圖片`,
                 `progressData`:`speed`,
                 `queueID`:`some_file_queue`,
                 `removeCompleted`:false,
                 `queueSizeLimit`:2,
                 `removeTimeout`:1,
                 `swf`           `${pageContext.request.contextPath}/scripts/uploadify.swf`,
                 <!--這是關鍵,上傳後臺處理的servlet地址-->
                 `uploader`      `${pageContext.request.contextPath}/uploadifyServlet`,
                 `multi`         false,
                 //加上此句會重寫onSelectError方法【需要重寫的事件】
                 `overrideEvents`: [`onSelectError``onDialogClose`,`onCancel`,`onClearQueue`],
                 `onCancel`:function(file){
                    console.log(file.name); 
                 },
                  
                 `onClearQueue`:function(queueItemCount){
                     console.log(queueItemCount);
                 },
                 `onDestroy`:function(){
                    console.log(`destory`); 
                 },
                 `onDialogClose`:function(queueData){
                     console.log(queueData.filesSelected );
                     console.log(queueData.filesQueued  );
                 },
                 `onUploadSuccess`:function(file,data,response){
                     $(`#` + file.id).find(`.data`).html(``);
                     console.log(`data=`+data);
                     $("#upload_org_code_name").val(data);
                     <!--這是關鍵,預覽後臺處理的servlet地址-->
                     $("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/getImgServlet?file="+data);  
                     $("#upload_org_code_img").show();
                 },
                
                 //返回一個錯誤,選擇檔案的時候觸發
                 `onSelectError`:function(file, errorCode, errorMsg){
                     switch(errorCode) {
                         case -110:
                             alert("檔案 ["+file.name+"] 大小超出系統限制的" + jQuery(`#upload_org_code`).uploadify(`settings``fileSizeLimit`) + "大小!");
                             break;
                         case -120:
                             alert("檔案 ["+file.name+"] 大小異常!");
                             break;
                         case -130:
                             alert("檔案 ["+file.name+"] 型別不正確!");
                             break;
                     }
                 },
             });
             
        });  
</script>  
</head>
<body>
<!--用於圖片預覽的顯示-->
<img style="display: none" id="upload_org_code_img" src="" width="100" height="100"/>
 
<input type="file" name="upload_org_code" id="upload_org_code"/>
<!--自定義的一個queue-->
<div id="some_file_queue">
 
</div>
 
 <!--一些操作啦-->
     <a href="javascript:jQuery(`#upload_org_code`).uploadify(`upload`,`*`);">上傳</a> 
      <a href="javascript:$(`#upload_org_code`).uploadify(`cancel`,`*`)">取消上傳</a>  
      <a href="javascript:$(`#upload_org_code`).uploadify(`destroy`)">destory</a>  
       
</body>
</html>


其中,js中定義了上傳處理的uploadifyServlet地址,所以下一步就是編寫改servlet了

uploadifyServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class uploadifyServlet extends HttpServlet {
     
       private String configPath="d:/image/";
         
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
      
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              String ret_fileName = null;//返回給前端已修改的圖片名稱
              request.setCharacterEncoding("UTF-8");
              response.setContentType("text/html; charset=UTF-8");
              PrintWriter out = response.getWriter();
              // 檔案儲存目錄路徑
              String savePath = configPath; 
        
              DiskFileItemFactory factory = new DiskFileItemFactory();
              ServletFileUpload upload = new ServletFileUpload(factory);
              upload.setHeaderEncoding("UTF-8");
              try {
                  List<?> items = upload.parseRequest(request);
                  Iterator<?> itr = items.iterator();
        
                  while (itr.hasNext()) {
                       
                      DiskFileItem item   = (DiskFileItem) itr.next();
                      String fileName = item.getName();
                      if(fileName!=null){
                          ret_fileName  = fileName;
                      }
                      if (!item.isFormField()) {
                          try {
                              File uploadedFile = new File(savePath,fileName);
        
                              OutputStream os = new FileOutputStream(uploadedFile);
                              InputStream is = item.getInputStream();
                              byte buf[] = new byte[1024];// 可以修改 1024 以提高讀取速度
                              int length = 0;
                              while ((length = is.read(buf)) > 0) {
                                  os.write(buf, 0, length);
                              }
                              // 關閉流
                              os.flush();
                              os.close();
                              is.close();
                          catch (Exception e) {
                              e.printStackTrace();
                          }
                      }
                     
                  }
        
              catch (FileUploadException e) {
                  e.printStackTrace();
              }
              //將已修改的圖片名稱返回前端
              out.print(ret_fileName);
              out.flush();
              out.close();
 
        }
}

上述程式碼的意思很簡單,將上傳的檔案放入指定的資料夾,並返回圖片的名稱。


到此為止,上傳就結束了,下面是預覽。


在onUploadSuccess中,我們得到了上傳成功圖片的返回的圖片名稱,其中我們定義了實現預覽效果的後臺servlet,getImgServlet


下面給出改servlet的程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class getImg extends HttpServlet {
     
       private String configPath="d:/image/";
         
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
      
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
             String file = request.getParameter("file");
             File pic = new File(configPath+file);
       
             FileInputStream fis = new FileInputStream(pic);
             OutputStream os = response.getOutputStream();
             try {
                 int count = 0;
                 byte[] buffer = new byte[1024 1024];
                 while ((count = fis.read(buffer)) != -1)
                     os.write(buffer, 0, count);
                 os.flush();
             catch (IOException e) {
                 e.printStackTrace();
             finally {
                 if (os != null)
                     os.close();
                 if (fis != null)
                     fis.close();
             }
               
        }
}

上述程式碼很簡單,得到傳過來的檔名之後,直接傳送檔案流過去,實現圖片顯示


具體的專案包地址如下,大家可直接下載執行:

http://yun.baidu.com/share/link?shareid=702477080&uk=2836507213

     本文轉自布拉君君 51CTO部落格,原文連結:http://blog.51cto.com/5148737/1588035,如需轉載請自行聯絡原作者


相關文章