【JSP】使用JQuery upload 進行AJAX上傳

JSP或一般網站開發常用的檔案上傳筆記。

重點步驟

1.UPLOAD_FILE為input type=”file”

2.加入change事件,當使用者選擇檔案後詢問是否確定上傳

3.進行觸發upload事件  用法: upload(url, [data], [callback], [type])

此範例使用upload(url, callback, type)

4.回應格式為json直接物件取值方式即可

 

html code

<input name="UPLOAD_FILE" id="UPLOAD_FILE" type="file"/>

jquery code

$('#UPLOAD_FILE').change(function(){
    if(confirm("是否確定上傳?")){
        $(this).upload('url', function(res) {
            if(res.status == 'OK'){
                alert(res.msg);
            }else if(res.status == 'NG'){
                alert(res.msg);
            }
        }, 'json');
    }
});

java code

 // 檔案上傳欄InputStream
 InputStream fileuploadIn = null; 
 //檔案上傳欄位 InputStream size
 int fileSize = 0;   
 // 限制最大上傳檔案容量5MB
 long maxsize = 1024 * 1024 * 5;  
 String status = "OK";
 String msg = "";
 JSONObject totalJason = new JSONObject();
   
 if("POST".equals(request.getMethod().toUpperCase())){
  DiskFileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload sfu  = new ServletFileUpload(factory);
  sfu.setSizeMax(maxsize);
  
  List items = null;
  try{
   // parse request
   items = sfu.parseRequest(request);
  }catch (Exception ex) {
   status = "NG";
   msg = "上傳失敗: 檔案大小超過5MB!!";
   totalJason.put("status", status);
   totalJason.put("msg", msg);
   response.reset();
   response.setCharacterEncoding("UTF-8");
   out.println(totalJason.toString());
   return;
  }
   Iterator it=items.iterator();
   
   while(it.hasNext())
   {
    FileItem item=(FileItem)it.next();
    if("UPLOAD_FILE".equals(item.getFieldName())){
     String filename=item.getName()!=null?item.getName():"";
     if("".equals(filename)){
      status = "NG";
      msg = "上傳失敗: 請選擇上傳檔案!!";
      totalJason.put("status", status);
      totalJason.put("msg", msg);
      response.reset();
      response.setCharacterEncoding("UTF-8");
      out.println(totalJason.toString());
      return;
     }
     
     if(filename.toUpperCase().indexOf(".JPG") < 0){
      status = "NG";
      msg = "上傳失敗: 檔案格式僅限.JPG!!";
      totalJason.put("status", status);
      totalJason.put("msg", msg);
      response.reset();
      response.setCharacterEncoding("UTF-8");
      out.println(totalJason.toString());
      return;
     }
     
     fileuploadIn = item.getInputStream();
     fileSize = (int) item.getSize();
    }
   }
 }
台北人,軟體工程師一枚,工作閒暇之餘記錄生活、分享整理資訊。
Posts created 105

發表迴響

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top