JavaWEB+Ajax實現檔案上傳

來源:互聯網
上載者:User

標籤:


準備:我們需要找一張綠色或者其它顏色的背景圖,放在photo檔案夾裡就好哈,然後加jar:common-io和commo-fileupload就可以哈


建立progress.css檔案:

.pro{  height:15px;  width:500px;  background: #FFFFF0;  border: 1px solid #8FBC8F;  margin: 0;  padding: 0;  display:none;  position: relative;  left:25px;  float:left;}


建立uploadAjax.js

function go(){ f1.submit(); document.getElementById("pro").style.display="block"; document.getElementById("prop").style.display=""; timer=setInterval("getP()",50);  } var xmlHttpRequest;function getP(){   if(window.XmlHttpRequest){  xmlHttpRequest=new XmlHttpRequest(); }else{  xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP"); }    xmlHttpRequest.onreadystatechange=callBack;  url="GetProgressServlet"; xmlHttpRequest.open("post",url,true);   xmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttpRequest.send("&timeStamp="+(new Date()).getTime());   }//回呼函數function callBack(){   if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200){      result=xmlHttpRequest.responseText;  var result=result.replace(/(^\s*)|(\s*$)/g, "");  var res=result.split(",");  var flag=res[1];   var per=parseInt(res[0]);  var err=res[2];  document.getElementById("imgpro").style.width=per*5+"px";  document.getElementById("prop").innerHTML=per+"%";  if(flag=="OK"){   window.clearInterval(timer);   alert("上傳成功!");   document.getElementById("pro").style.display="none";   document.getElementById("prop").innerHTML="";   f1.reset();  }  if(err!=""||err.length>0){   window.clearInterval(timer);   alert(err);  }  if(flag==null){   window.clearInterval(timer);  } }}


調用和引入


<link rel="stylesheet" type="text/css" href="css/progress.css">
<script type="text/javascript" src="js/uploadAjax.js" charset="UTF-8"></script>
   


<div class="am-g">      <div class="am-u-sm-12" align="left">    <div class="am-form-group"><form action="<%=basePath %>UploadSpotImgServlet" name="f1" id="f1" method="post" enctype="multipart/form-data" target="if"> <div class="field">                <a class="button input-file" href="javascript:void(0);">+ 瀏覽檔案<input size="30" type="file" name="logo" data-validate="required:請選擇上傳檔案,regexp#.+.(jpg|jpeg|png|gif)$:只能上傳jpg|gif|png格式檔案" /></a>             </div>             <br>             <input type="reset" name="res1" value="重設"  class="am-btn am-btn-primary" />             <input type="submit" name="but1" value="提交" onclick="go();" class="am-btn am-btn-primary" /></form><br><div id="pro" class="pro" align="left" style="height:1px;width:600px;"> <img alt="" src="photo/progress.png" width="0px" id="imgpro"></div>  <span id="prop" style="width:15px;height:15px;display: none;">0%</span>  <br><br><iframe id="if" name="if" src="" style="display: none"></iframe>   </div>     </div>   </div>

建立UploadSpotImgServlet

public class UploadSpotImgServlet extends HttpServlet {/** *  */private static final long serialVersionUID = 1L;private String fileName;private File tempFile;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//設定編碼格式為utf-8response.setContentType("text/html;charset=UTF-8");PrintWriter out1 = response.getWriter();request.setCharacterEncoding("UTF-8");//擷取session,儲存進度和上傳結果,上傳結果初始值為NOK,當為Ok表示上傳完成HttpSession session=request.getSession();session.setAttribute("prog", "0");session.setAttribute("result", "NOK"); session.setAttribute("error", "");String error="";//給上傳的檔案設一個最大值,這裡是不得超過50MBint maxSize=50*1024*1024;//建立工廠對象和檔案上傳對象DiskFileItemFactory factory=new DiskFileItemFactory();ServletFileUpload upload=new ServletFileUpload(factory);try {//解析上傳請求List items=upload.parseRequest(request);Iterator itr=items.iterator();       while(itr.hasNext()){    FileItem item=(FileItem)itr.next();    //判斷是否為檔案域    if(!item.isFormField()){     if(item.getName()!=null&&!item.getName().equals("")){      //擷取上傳檔案大小和檔案名稱      long upFileSize=item.getSize();         fileName=item.getName();      if(upFileSize>maxSize){       error="您上傳的檔案太大了,請選擇不超過50MB的檔案!";       break;      }      //此時檔案暫存在伺服器的記憶體中,構造臨時對象      tempFile=new File(fileName);      //指定檔案上傳伺服器的目錄及檔案名稱      File file=new File("D:\\MyEclipse\\workspace\\TourismSystemServer\\WebRoot\\source\\images",tempFile.getName());      //構造輸入資料流讀檔案      InputStream is=item.getInputStream();      int length=0;      byte[] by=new byte[1024];      double persent=0;      FileOutputStream fos=new FileOutputStream(file);      PrintWriter out=response.getWriter();      while((length=is.read(by))!=-1){       //計算檔案進度       persent+=length/(double)upFileSize*100D;       fos.write(by, 0, length);       session.setAttribute("prog", Math.round(persent)+"");        Thread.sleep(10);      }      fos.close();      Thread.sleep(1000);     }else{     error="沒選擇上傳檔案!";     }    }   }     Constant.ImgPath.path = "/source/images/"+tempFile.getName();  //System.out.println(Constant.ImgPath.path);   response.sendRedirect(Constant.WEB_URL_ADDSPOTINFO);   } catch (Exception e) {e.printStackTrace();error="上傳檔案出現錯誤:"+e.getMessage();}if(!error.equals("")){ session.setAttribute("error", error);}else{session.setAttribute("result", "OK");}out1.flush();out1.close();} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}

ok,這樣我們就可以上傳檔案到我們制定的檔案夾裡哦,還有結合Ajax,就不會出現頁面重新整理的情況了哦!




JavaWEB+Ajax實現檔案上傳

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.