網路上傳檔案功能實現步驟總結
阿新 • • 發佈:2020-07-17
檔案上傳步驟
1. 導包
匯入commons-io
和commons-fileupload
jar包
2. 前端頁面
action:頁面請求,需和web.xml
中匹配
method:設定為post
,沒有檔案大小限制
enctype:值為multipart/form-data
用於識別是否為檔案表單還是普通文字表單
<form action="upload.do" enctype="multipart/form-data" method="post"> <input type="file" name="file1"> <br> <input type="file" name="file2"> <br> <input type="submit"> <br> </form>
3. 註冊web.xml
<servlet> <servlet-name>FileUploadServlet</servlet-name> <servlet-class>com.juyss.servlet.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileUploadServlet</servlet-name> <url-pattern>/upload.do</url-pattern> </servlet-mapping>
4. 編寫Servlet
實現步驟
-
判斷表單為普通文字表單還是檔案表單
-
建立上傳檔案的儲存根路徑
-
建立臨時檔案的儲存根路徑
-
獲取
FileItem
物件 需要
ServletFileUpload
物件 需要用到
DiskFileItemFactory
物件,用於處理上傳路徑和限制檔案大小 -
通過
FileItem
物件獲取檔名,檔案字尾 -
使用UUID建立唯一儲存路徑
-
使用
fileItem.getInputStream()
獲取檔案輸入流 -
建立檔案輸出流
FileOutputStream fos = new FileOutputStream(savePath + "/" + fileName)
-
關閉流資源,同時刪除臨時檔案
fileItem.delete()
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("進入了FileUploadServlet.class");
//判斷表單是否為帶有檔案的表單
if (!ServletFileUpload.isMultipartContent(request)) {
return; //終止方法執行
}
//定義檔案上傳後儲存的根路徑
String rootPath = this.getServletContext().getRealPath("/WEB-INF/upload");
File rootFile = new File(rootPath);
if (!rootFile.exists()) {
rootFile.mkdir();
}
//定義檔案快取路徑
String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
File tempFile = new File(tempPath);
if (!tempFile.exists()) {
tempFile.mkdir();
}
//建立DiskFileItemFactory物件,處理上傳路徑和限制檔案大小
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(1024 * 1024, tempFile);
//建立ServletFileUpload物件
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
//獲取FileItem物件
List<FileItem> fileItems = null;
try {
fileItems = servletFileUpload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
if (fileItems==null){
System.out.println("fileItem空指標");
return;
}
Iterator<FileItem> iterator = fileItems.iterator();
//遍歷fileItems集合
while (iterator.hasNext()) {
FileItem fileItem = iterator.next();
if (fileItem.isFormField()) {//是普通文字表單
continue; //跳出迴圈
} else {//是檔案表單
//獲取檔案欄位名,標籤中name屬性的值
String fieldName = fileItem.getFieldName();
//獲取檔案上傳欄位中的檔名,一般來說為為檔名(不包含路徑資訊),在opera瀏覽器中可能會包含檔案路徑資訊
String name = fileItem.getName();
System.out.println("檔案欄位名:"+fieldName);
System.out.println("檔名:"+name);
//判斷檔名是否合法
if (name.trim().equals("") || name == null) {
continue;
}
//獲取檔名和檔案字尾
String fileName; //檔名
if (name.contains("/")){ //判斷name是否包含路徑資訊
fileName = name.substring(name.lastIndexOf("/"));
}else{
fileName = name;
}
String fileExtension = fileName.substring(fileName.indexOf(".") + 1);//獲取檔案字尾
System.out.println("檔名:" + fileName);
System.out.println("檔案型別:" + fileExtension);
//獲取隨機UUID
String uuid = UUID.randomUUID().toString();
//使用uuid建立唯一的資料夾作為檔案存放路徑
String savePath = rootPath + "/" + uuid; //檔案存放路徑
File savePathFile = new File(savePath);
if (!savePathFile.exists()) { //路徑不存在就建立
savePathFile.mkdir();
}
//獲取輸入流讀取上傳的檔案
InputStream is = fileItem.getInputStream();
//用輸出流儲存到本地
FileOutputStream fos = new FileOutputStream(savePath + "/" + fileName);
int len;
byte[] bytes = new byte[1024 * 1024];
while((len = is.read(bytes))!=-1){
fos.write(bytes,0,len);
}
fos.close();
is.close();
//刪除臨時檔案
fileItem.delete();
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}