javaweb實現文件上傳功能
更新時間:2022年06月22日 11:05:22 作者:深藍夢夕陽
這篇文章主要為大家詳細介紹了javaweb實現文件上傳功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了javaweb實現文件上傳的具體代碼,供大家參考,具體內容如下
1、創(chuàng)建一個空項目
2、新建一個web application 的Module
3、創(chuàng)建一個lib目錄導入需要用的jar包
- commons-io
- commons-fileupload
4、將lib包添加到項目依賴(右鍵 Add as Library)
5、編寫文件上傳表單
<%--通過表單上傳文件 ? ? get : 上傳文件大小有限制 ? ? post : 上傳文件大小沒有限制 ? ? 上傳文件必須要enctype="multipart/form-data" --%> ? <form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data"> ? ? <p>上傳用戶:<input type="text" name="username"></p> ? ? <p><input type="file" name="file1"></p> ? ? <p><input type="submit"> | <input type="reset"></p> ? </form>
6.編寫Servlet
public class FileServlet extends HttpServlet { ? ? protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ? ? ? ? //判斷上傳的表單是普通表單還是帶文件表單 ? ? ? ? if (!ServletFileUpload.isMultipartContent(request)){//如果不是帶文件表單 ? ? ? ? ? ? return;//終止方法運行,直接返回 ? ? ? ? } ? ? ? ? try { ? ? ? ? //創(chuàng)建上傳文件的保存路徑,建議在WEB-INF路徑下,安全,用戶無法直接訪問上傳的文件. ? ? ? ? String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); ? ? ? ? File uploadFile = new File(uploadPath); ? ? ? ? if (!uploadFile.exists()){ ? ? ? ? ? ? uploadFile.mkdirs();//如果不存在則創(chuàng)建目錄 ? ? ? ? } ? ? ? ? //緩存,臨時文件 ? ? ? ? //臨時文件,假如文件超出預期大小,就把它放到臨時文件夾中,過幾天自動刪除,或者提醒用戶轉存為永久文件 ? ? ? ? String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp"); ? ? ? ? File tmpFile = new File(tmpPath); ? ? ? ? if (!tmpFile.exists()){ ? ? ? ? ? ? tmpFile.mkdirs();//如果不存在則創(chuàng)建臨時目錄 ? ? ? ? } ? ? ? ? //1.創(chuàng)建DiskFileItemFactory對象,處理文件上傳路徑或者大小限制 ? ? ? ? DiskFileItemFactory factory = new DiskFileItemFactory(); ? ? ? ? //通過這個工廠設置一個緩沖區(qū),當上傳的文件大于這個緩沖區(qū)的時候,將它放在臨時文件中 ? ? ? ? factory.setSizeThreshold(1024*1024);//緩沖區(qū)大小為1M ? ? ? ? factory.setRepository(tmpFile);//臨時文件的保存目錄 ? ? ? ? //2.獲取ServletFileUpload對象 ? ? ? ? ServletFileUpload upload = new ServletFileUpload(factory); ? ? ? ? //監(jiān)聽文件上傳進度 ? ? ? ? upload.setProgressListener(new ProgressListener() { ? ? ? ? ? ? @Override ? ? ? ? ? ? public void update(long l, long l1, int i) { ? ? ? ? ? ? ? ? System.out.println("總大小: "+l1+" 已上傳: "+l); ? ? ? ? ? ? } ? ? ? ? }); ? ? ? ? //處理亂碼問題 ? ? ? ? upload.setHeaderEncoding("utf-8"); ? ? ? ? //設置單個文件的最大值 ? ? ? ? upload.setFileSizeMax(1024*1024*10);//10M ? ? ? ? //設置總共能夠上傳文件的大小 ? ? ? ? upload.setSizeMax(1024*1024*10);//10M ? ? ? ? //3.處理上傳文件 ? ? ? ? ? ? //把前端請求解析,封裝成一個FileItem對象 ? ? ? ? ? ? List<FileItem> fileItems = upload.parseRequest(request); ? ? ? ? ? ? for (FileItem fileItem : fileItems) { ? ? ? ? ? ? ? ? //判斷上傳的表單是普通表單還是帶文件表單 ? ? ? ? ? ? ? ? if (fileItem.isFormField()){ ? ? ? ? ? ? ? ? ? ? String name=fileItem.getFieldName();//獲取表單控件的名字 ? ? ? ? ? ? ? ? ? ? String value=fileItem.getString("UTF-8");//獲取值,處理亂碼 ? ? ? ? ? ? ? ? ? ? System.out.println(name+": "+value); ? ? ? ? ? ? ? ? }else {//文件 ? ? ? ? ? ? ? ? ? ? String uploadFileName = fileItem.getName();//獲取上傳文件名字(帶路徑) ? ? ? ? ? ? ? ? ? ? //可能存在文件名不合法的情況 ? ? ? ? ? ? ? ? ? ? if (uploadFileName==null||uploadFileName.trim().equals("")){ ? ? ? ? ? ? ? ? ? ? ? ? continue; ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? //截取上傳的文件名 ? ? ? ? ? ? ? ? ? ? String FileName=uploadFileName.substring(uploadFileName.lastIndexOf("/")+1);//從最后一個/后開始截取 ? ? ? ? ? ? ? ? ? ? //截取后綴名 ? ? ? ? ? ? ? ? ? ? String fileExtName=uploadFileName.substring(uploadFileName.lastIndexOf(".")+1);//從最后一個.后開始截取 ? ? ? ? ? ? ? ? ? ? //網絡傳輸中的東西,都需要序列化 ? ? ? ? ? ? ? ? ? ? //POJO , 實體類, 如果想要在多個電腦運行, 傳輸-->需要把對象序列化 ? ? ? ? ? ? ? ? ? ? //JNI= java native Interface ? ? ? ? ? ? ? ? ? ? //implements Serializable : 標記接口 , JVM-->java棧 本地方法棧 native -->C++ ? ? ? ? ? ? ? ? ? ? //可以使用UUID(唯一標識的通用碼),保證文件名唯一 ? ? ? ? ? ? ? ? ? ? String uuidPath = UUID.randomUUID().toString();//生成一共隨機的uuid ? ? ? ? ? ? ? ? ? ? //==========================創(chuàng)建存放目錄========================// ? ? ? ? ? ? ? ? ? ? String realPath= uploadPath+"/"+uuidPath; ? ? ? ? ? ? ? ? ? ? //給每個文件創(chuàng)建一個對應的文件夾 ? ? ? ? ? ? ? ? ? ? File realPathFile = new File(realPath); ? ? ? ? ? ? ? ? ? ? if (!realPathFile.exists()){ ? ? ? ? ? ? ? ? ? ? ? ? realPathFile.mkdirs(); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? //==========================文件傳輸====================================// ? ? ? ? ? ? ? ? ? ? //獲取文件上傳的流 ? ? ? ? ? ? ? ? ? ? InputStream inputStream = fileItem.getInputStream(); ? ? ? ? ? ? ? ? ? ? //創(chuàng)建一個輸出文件的流 ? ? ? ? ? ? ? ? ? ? FileOutputStream fos = new FileOutputStream(realPath + "/" + FileName); ? ? ? ? ? ? ? ? ? ? //創(chuàng)建緩沖區(qū) ? ? ? ? ? ? ? ? ? ? byte[] buffer=new byte[1024]; ? ? ? ? ? ? ? ? ? ? //判斷是否讀取完畢 ? ? ? ? ? ? ? ? ? ? int len=0; ? ? ? ? ? ? ? ? ? ? while ((len=inputStream.read(buffer))>0){ ? ? ? ? ? ? ? ? ? ? ? ? fos.write(buffer,0,len); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? //關閉流 ? ? ? ? ? ? ? ? ? ? fos.close(); ? ? ? ? ? ? ? ? ? ? inputStream.close(); ? ? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } catch (FileUploadException e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? } }
7.注冊Servlet
<servlet> ? ? <servlet-name>FileServlet</servlet-name> ? ? <servlet-class>com.kuang.servlet.FileServlet</servlet-class> </servlet> <servlet-mapping> ? ? <servlet-name>FileServlet</servlet-name> ? ? <url-pattern>/upload.do</url-pattern> </servlet-mapping>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SpringBoot中?Jackson?日期的時區(qū)和日期格式問題解決
因為最近項目需要國際化,需要能夠支持多種國際化語言,目前需要支持三種(法語、英語、簡體中文),這篇文章主要介紹了SpringBoot中?Jackson?日期的時區(qū)和日期格式問題,需要的朋友可以參考下2022-12-12SpringCloud HystrixDashboard服務監(jiān)控詳解
Hystrix Dashboard 是Spring Cloud中查看Hystrix實例執(zhí)行情況的一種儀表盤組件,支持查看單個實例和查看集群實例,本文將對其服務監(jiān)控學習2022-11-11IDEA Maven Mybatis generator 自動生成代碼(實例講解)
下面小編就為大家分享一篇IDEA Maven Mybatis generator 自動生成代碼的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12