精品熟女碰碰人人a久久,多姿,欧美欧美a v日韩中文字幕,日本福利片秋霞国产午夜,欧美成人禁片在线观看

Jsp+Servlet實現文件上傳下載 文件上傳(一)

文件上傳和下載功能是java web必備技能,很實用。

本文使用的是apache下的著名的文件上傳組件
org.apache.commons.fileupload 實現

下面結合最近看到的一些資料以及自己的嘗試,先寫第一篇文件上傳。后續會逐步實現下載,展示文件列表,上傳信息持久化等。

廢話少說,直接上代碼

第一步、引用jar包,設置上傳目錄

commons-fileupload-1.3.1.jar
commons-io-2.4.jar

上傳目錄:web-inf/tempfiles和web-inf/uploadfiles

第二步、編寫jsp頁面

<%@ page contenttype="text/html;charset=utf-8" language="java" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<html> 
<head> 
 <title>文件上傳測試</title> 
</head> 
<body> 
<form method="post" enctype="multipart/form-data" action="<%=request.getcontextpath()%>/uploadservlet"> 
 文件: <input type="file" name="upfile"><br/> 
 <br/> 
 <input type="submit" value="上傳"> 
</form> 
<c:if test="${not empty errormessage}"> 
 <input type="text" id="errormessage" value="${errormessage}" style="color:red;" disabled="disabled"> 
</c:if> 
</body> 
</html> 

第三步、編寫servlet,處理文件上傳的核心

package servlet; 
 
import org.apache.commons.fileupload.fileitem; 
import org.apache.commons.fileupload.fileuploadbase; 
import org.apache.commons.fileupload.fileuploadexception; 
import org.apache.commons.fileupload.progresslistener; 
import org.apache.commons.fileupload.disk.diskfileitemfactory; 
import org.apache.commons.fileupload.servlet.servletfileupload; 
 
import javax.servlet.servletexception; 
import javax.servlet.annotation.webservlet; 
import javax.servlet.http.httpservlet; 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
import java.io.file; 
import java.io.fileoutputstream; 
import java.io.ioexception; 
import java.io.inputstream; 
import java.util.calendar; 
import java.util.iterator; 
import java.util.list; 
import java.util.uuid; 
 
/** 
 * 處理文件上傳 
 * 
 * @author xusucheng 
 * @create 2017-12-27 
 **/ 
@webservlet("/uploadservlet") 
public class uploadservlet extends httpservlet { 
 @override 
 protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { 
 //設置文件上傳基本路徑 
 string savepath = this.getservletcontext().getrealpath("/web-inf/uploadfiles"); 
 //設置臨時文件路徑 
 string temppath = this.getservletcontext().getrealpath("/web-inf/tempfiles"); 
 file tempfile = new file(temppath); 
 if (!tempfile.exists()) { 
 tempfile.mkdir(); 
 } 
 
 //定義異常消息 
 string errormessage = ""; 
 //創建file items工廠 
 diskfileitemfactory factory = new diskfileitemfactory(); 
 //設置緩沖區大小 
 factory.setsizethreshold(1024 * 100); 
 //設置臨時文件路徑 
 factory.setrepository(tempfile); 
 //創建文件上傳處理器 
 servletfileupload upload = new servletfileupload(factory); 
 //監聽文件上傳進度 
 progresslistener progresslistener = new progresslistener() { 
 public void update(long pbytesread, long pcontentlength, int pitems) { 
 system.out.println("正在讀取文件: " + pitems); 
 if (pcontentlength == -1) { 
  system.out.println("已讀取: " + pbytesread + " 剩余0"); 
 } else { 
  system.out.println("文件總大小:" + pcontentlength + " 已讀取:" + pbytesread); 
 } 
 } 
 }; 
 upload.setprogresslistener(progresslistener); 
 
 //解決上傳文件名的中文亂碼 
 upload.setheaderencoding("utf-8"); 
 //判斷提交上來的數據是否是上傳表單的數據 
 if (!servletfileupload.ismultipartcontent(request)) { 
 //按照傳統方式獲取數據 
 return; 
 } 
 
 //設置上傳單個文件的大小的最大值,目前是設置為1024*1024字節,也就是1mb 
 upload.setfilesizemax(1024 * 1024); 
 //設置上傳文件總量的最大值,最大值=同時上傳的多個文件的大小的最大值的和,目前設置為10mb 
 upload.setsizemax(1024 * 1024 * 10); 
 
 try { 
 //使用servletfileupload解析器解析上傳數據,解析結果返回的是一個list<fileitem>集合,每一個fileitem對應一個form表單的輸入項 
 list<fileitem> items = upload.parserequest(request); 
 iterator<fileitem> iterator = items.iterator(); 
 while (iterator.hasnext()) { 
 fileitem item = iterator.next(); 
 
 //判斷jsp提交過來的是不是文件 
 if (item.isformfield()) { 
  errormessage = "請提交文件!"; 
  break; 
 } else { 
  //文件名 
  string filename = item.getname(); 
  if (filename == null || filename.trim() == "") { 
  system.out.println("文件名為空!"); 
  } 
  //處理不同瀏覽器提交的文件名帶路徑問題 
  filename = filename.substring(filename.lastindexof("\\") + 1); 
  //文件擴展名 
  string fileextension = filename.substring(filename.lastindexof(".") + 1); 
  //判斷擴展名是否合法 
  if (!validextension(fileextension)) { 
  errormessage = "上傳文件非法!"; 
  item.delete(); 
  break; 
  } 
  //獲得文件輸入流 
  inputstream in = item.getinputstream(); 
  //得到保存文件的名稱 
  string savefilename = createfilename(filename); 
  //得到文件保存路徑 
  string realfilepath = createrealfilepath(savepath, savefilename); 
  //創建文件輸出流 
  fileoutputstream out = new fileoutputstream(realfilepath); 
  //創建緩沖區 
  byte buffer[] = new byte[1024]; 
  int len = 0; 
  while ((len = in.read(buffer)) > 0) { 
  //寫文件 
  out.write(buffer, 0, len); 
  } 
  //關閉輸入流 
  in.close(); 
  //關閉輸出流 
  out.close(); 
  //刪除臨時文件 todo 
  item.delete(); 
  //將上傳文件信息保存到附件表中 todo 
 } 
 
 } 
 
 } catch (fileuploadbase.filesizelimitexceededexception e) { 
 e.printstacktrace(); 
 request.setattribute("errormessage", "單個文件超出最大值!!!"); 
 request.getrequestdispatcher("pages/upload/upload.jsp").forward(request, response); 
 return; 
 } catch (fileuploadbase.sizelimitexceededexception e) { 
 e.printstacktrace(); 
 request.setattribute("errormessage", "上傳文件的總的大小超出限制的最大值!!!"); 
 request.getrequestdispatcher("pages/upload/upload.jsp").forward(request, response); 
 return; 
 } catch (fileuploadexception e) { 
 e.printstacktrace(); 
 request.setattribute("errormessage", "文件上傳失敗!!!"); 
 request.getrequestdispatcher("pages/upload/upload.jsp").forward(request, response); 
 return; 
 } 
 
 request.setattribute("errormessage", errormessage); 
 request.getrequestdispatcher("pages/upload/upload.jsp").forward(request, response); 
 
 
 } 
 
 @override 
 protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { 
 doget(request, response); 
 } 
 
 private boolean validextension(string fileextension) { 
 string[] exts = {"jpg", "txt", "doc", "pdf"}; 
 for (int i = 0; i < exts.length; i++) { 
 if (fileextension.equals(exts[i])) { 
 return true; 
 } 
 
 } 
 
 return false; 
 } 
 
 private string createfilename(string filename) { 
 return uuid.randomuuid().tostring() + "_" + filename; 
 } 
 
 /** 
 * 根據基本路徑和文件名稱生成真實文件路徑,基本路徑\\年\\月\\filename 
 * 
 * @param basepath 
 * @param filename 
 * @return 
 */ 
 private string createrealfilepath(string basepath, string filename) { 
 calendar today = calendar.getinstance(); 
 string year = string.valueof(today.get(calendar.year)); 
 string month = string.valueof(today.get(calendar.month) + 1); 
 
 
 string uppath = basepath + file.separator + year + file.separator + month + file.separator; 
 file uploadfolder = new file(uppath); 
 if (!uploadfolder.exists()) { 
 uploadfolder.mkdirs(); 
 } 
 
 string realfilepath = uppath + filename; 
 
 return realfilepath; 
 } 
} 

第四步、測試

http://localhost:8080/helloweb/pages/upload/upload.jsp

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持碩編程。

相關文章