JavaWeb實(shí)現(xiàn)簡(jiǎn)單上傳文件功能
本文實(shí)例為大家分享了JavaWeb實(shí)現(xiàn)上傳文件功能的具體代碼,供大家參考,具體內(nèi)容如下
基本思想:網(wǎng)站服務(wù)器的內(nèi)部除了有Web應(yīng)用,還有文件系統(tǒng),客戶端向網(wǎng)站上傳文件就是將文件以流的形式傳輸給了服務(wù)器,如圖所示:
注意事項(xiàng):
1、為保證服務(wù)器的安全,上傳的文件路徑應(yīng)放在外界不能直接訪問(wèn)的目錄下,比如WEB-INF目錄下。
2、因?yàn)榉?wù)器的文件系統(tǒng)大小有限,上傳的文件大小必須要有限制。
3、為防止因?yàn)槲募貜?fù)而導(dǎo)致文件覆蓋,應(yīng)當(dāng)給上傳的文件夾生成唯一的標(biāo)識(shí),比如時(shí)間戳、UUID或者md5加密。
4、可以限制上傳文件的類型,在收到文件的時(shí)候,判斷文件后綴是否合法。
在JavaWeb中,一般我們使用ServletFileUpload類來(lái)處理上傳的文件數(shù)據(jù),它使用parseRequest方法將表單的每一個(gè)輸入項(xiàng)封裝成一個(gè)FileItem對(duì)象,并以list的形式返回,處理數(shù)據(jù)比較簡(jiǎn)短,方便。
下面是一個(gè)上傳文件的小demo,編輯器是IDEA,項(xiàng)目類型是Maven Webapp。
package com.xiaojing.servlet; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; import java.util.UUID; public class FileUploadServlet extends HttpServlet { ? ? @Override ? ? protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ? ? ? ? //判斷表單是普通表單,還是上傳文件表單 ? ? ? ? if(!ServletFileUpload.isMultipartContent(req)){ ? ? ? ? ? ? return; ? ? ? ? } ? ? ? ? //創(chuàng)建上傳文件的路徑,一般放在/WEB-INF下,比較安全 ? ? ? ? String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); ? ? ? ? File uploadFile = new File(uploadPath); ? ? ? ? if(!uploadFile.exists()){ ? ? ? ? ? ? uploadFile.mkdir(); ? ? ? ? } ? ? ? ? //如果上傳的文件大小超過(guò)了限制,那么會(huì)將這個(gè)文件放在臨時(shí)文件夾,過(guò)段時(shí)間提醒用戶刪除或者轉(zhuǎn)為永久 ? ? ? ? String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); ? ? ? ? File tempFile = new File(tempPath); ? ? ? ? if(!tempFile.exists()){ ? ? ? ? ? ? tempFile.mkdir(); ? ? ? ? } ? ? ? ? //1、創(chuàng)建DiskFileItemFactory對(duì)象 ? ? ? ? DiskFileItemFactory factory = new DiskFileItemFactory(); ? ? ? ? //2、獲取ServletFileUpload對(duì)象 ? ? ? ? ServletFileUpload upload = new ServletFileUpload(); ? ? ? ? upload.setFileItemFactory(factory); ? ? ? ? //3、處理上傳文件 ? ? ? ? ? ? //將前端請(qǐng)求封裝成Fileitem對(duì)象,每一個(gè)表單輸入項(xiàng)都是一個(gè)Fileitem對(duì)象 ? ? ? ? try { ? ? ? ? ? ? List<FileItem> items = upload.parseRequest(req); ? ? ? ? ? ? for (FileItem item: items) { ? ? ? ? ? ? ? ? if(item.isFormField()){ //如果是普通的表單 ? ? ? ? ? ? ? ? ? ? //getFieldName()是input的name屬性,getString()是input的value屬性 ? ? ? ? ? ? ? ? ? ? String fieldName = item.getFieldName(); ? ? ? ? ? ? ? ? ? ? String value = item.getString("UTF-8"); ? ? ? ? ? ? ? ? ? ? System.out.println(fieldName + ":" +value); ? ? ? ? ? ? ? ? }else{ ?//上傳文件的表單 ? ? ? ? ? ? ? ? ? ? //---------------處理文件------------------// ? ? ? ? ? ? ? ? ? ? String uploadFileName = item.getName(); ? ? ? ? ? ? ? ? ? ? System.out.println("上傳的文件名:"+uploadFileName); ? ? ? ? ? ? ? ? ? ? if(uploadFileName == null || uploadFileName.trim().equals("")){ ? ? ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? //獲取fileName文件名,uploadFileName一般是url/文件路徑/文件 ? ? ? ? ? ? ? ? ? ? String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("\\")+1); ? ? ? ? ? ? ? ? ? ? //獲取文件后綴 ? ? ? ? ? ? ? ? ? ? String fileExt = uploadFileName.substring(uploadFileName.lastIndexOf(".")+1); ? ? ? ? ? ? ? ? ? ? System.out.println("文件信息:"+fileName); ? ? ? ? ? ? ? ? ? ? //---------------處理地址-----------------// ? ? ? ? ? ? ? ? ? ? //使用UUID唯一標(biāo)識(shí)存放文件夾 ? ? ? ? ? ? ? ? ? ? String uuidPath = UUID.randomUUID().toString(); ? ? ? ? ? ? ? ? ? ? //獲取真實(shí)的文件夾地址 ? ? ? ? ? ? ? ? ? ? String realPath = uploadPath + "/" + uuidPath; ? ? ? ? ? ? ? ? ? ? File realFile = new File(realPath); ? ? ? ? ? ? ? ? ? ? if(!realFile.exists()){ ? ? ? ? ? ? ? ? ? ? ? ? realFile.mkdir(); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? //---------------處理文件流-----------------// ? ? ? ? ? ? ? ? ? ? //獲取文件上傳的流 ? ? ? ? ? ? ? ? ? ? InputStream inputStream = item.getInputStream(); ? ? ? ? ? ? ? ? ? ? //創(chuàng)建一個(gè)文件輸出流 ? ? ? ? ? ? ? ? ? ? FileOutputStream outputStream = new FileOutputStream(realFile + "/" + fileName); ? ? ? ? ? ? ? ? ? ? //創(chuàng)建一個(gè)緩沖區(qū) ? ? ? ? ? ? ? ? ? ? byte[] buffer = new byte[1024 * 1024]; ? ? ? ? ? ? ? ? ? ? int len = 0; ? ? ? ? ? ? ? ? ? ? while((len = inputStream.read(buffer)) > 0){ //每次讀寫(xiě)1M ? ? ? ? ? ? ? ? ? ? ? ? outputStream.write(buffer,0,len); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? outputStream.close(); ? ? ? ? ? ? ? ? ? ? inputStream.close(); ? ? ? ? ? ? ? ? ? ? String msg = "文件上傳成功"; ? ? ? ? ? ? ? ? ? ? System.out.println("文件上傳成功"); ? ? ? ? ? ? ? ? ? ? //清除臨時(shí)文件 ? ? ? ? ? ? ? ? ? ? item.delete(); ? ? ? ? ? ? ? ? ? ? //轉(zhuǎn)發(fā) ? ? ? ? ? ? ? ? ? ? req.setAttribute("msg",msg); ? ? ? ? ? ? ? ? ? ? req.getRequestDispatcher("index.jsp").forward(req,resp); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } catch (FileUploadException e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? } ? ? @Override ? ? protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ? ? ? ? doGet(req, resp); ? ? } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java實(shí)戰(zhàn)之圖書(shū)管理系統(tǒng)的實(shí)現(xiàn)
這篇文章主要介紹了如何利用Java語(yǔ)言編寫(xiě)一個(gè)圖書(shū)管理系統(tǒng),文中采用的技術(shù)有Springboot、SpringMVC、MyBatis、ThymeLeaf 等,需要的可以參考一下2022-03-03java.sql.SQLException:com.mysql.cj.jdbc.Driver報(bào)錯(cuò)問(wèn)題解決
這篇文章主要給大家介紹了關(guān)于java.sql.SQLException:com.mysql.cj.jdbc.Driver報(bào)錯(cuò)問(wèn)題解決的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-08-08關(guān)于Controller層和Service層的類報(bào)錯(cuò)問(wèn)題及解決方案
這篇文章主要介紹了關(guān)于Controller層和Service層的類報(bào)錯(cuò)問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02IDEA中WebService生成Java代碼并調(diào)用外部接口實(shí)現(xiàn)代碼
這篇文章主要介紹了IDEA中WebService生成Java代碼并調(diào)用外部接口實(shí)現(xiàn),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05基于bufferedreader的read()與readline()讀取出錯(cuò)原因及解決
這篇文章主要介紹了bufferedreader的read()與readline()讀取出錯(cuò)原因及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Java獲取項(xiàng)目路徑方式System.getProperty(“user.dir“)
這篇文章主要介紹了Java獲取項(xiàng)目路徑方式System.getProperty(“user.dir“),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12