message.jsp的代碼如下:<\/p>
<%@ page language=\"java\" pageEncoding=\"UTF-8\"%>\n\n\n \n 消息提示<\/title>\n <\/head>\n \n 亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱\n ${message}\n <\/body>\n<\/html><\/pre>2.2、處理文件上傳的Servlet<\/p>UploadHandleServlet的代碼如下:<\/p>package me.gacl.web.controller;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.List;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.apache.commons.fileupload.FileItem;\nimport org.apache.commons.fileupload.disk.DiskFileItemFactory;\nimport org.apache.commons.fileupload.servlet.ServletFileUpload;\n\npublic class UploadHandleServlet extends HttpServlet {\n\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \/\/得到上傳文件的保存目錄,將上傳的文件存放于WEB-INF目錄下,不允許外界直接訪問,保證上傳文件的安全\n String savePath = this.getServletContext().getRealPath(\"\/WEB-INF\/upload\");\n File file = new File(savePath);\n \/\/判斷上傳文件的保存目錄是否存在\n if (!file.exists() && !file.isDirectory()) {\n System.out.println(savePath+\"目錄不存在,需要創(chuàng)建\");\n \/\/創(chuàng)建目錄\n file.mkdir();\n }\n \/\/消息提示\n String message = \"\";\n try{\n \/\/使用Apache文件上傳組件處理文件上傳步驟:\n \/\/1、創(chuàng)建一個DiskFileItemFactory工廠\n DiskFileItemFactory factory = new DiskFileItemFactory();\n \/\/2、創(chuàng)建一個文件上傳解析器\n ServletFileUpload upload = new ServletFileUpload(factory);\n \/\/解決上傳文件名的中文亂碼\n upload.setHeaderEncoding(\"UTF-8\"); \n \/\/3、判斷提交上來的數(shù)據(jù)是否是上傳表單的數(shù)據(jù)\n if(!ServletFileUpload.isMultipartContent(request)){\n \/\/按照傳統(tǒng)方式獲取數(shù)據(jù)\n return;\n }\n \/\/4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結果返回的是一個List集合,每一個FileItem對應一個Form表單的輸入項\n List list = upload.parseRequest(request);\n for(FileItem item : list){\n \/\/如果fileitem中封裝的是普通輸入項的數(shù)據(jù)\n if(item.isFormField()){\n String name = item.getFieldName();\n \/\/解決普通輸入項的數(shù)據(jù)的中文亂碼問題\n String value = item.getString(\"UTF-8\");\n \/\/value = new String(value.getBytes(\"iso8859-1\"),\"UTF-8\");\n System.out.println(name + \"=\" + value);\n }else{\/\/如果fileitem中封裝的是上傳文件\n \/\/得到上傳的文件名稱,\n String filename = item.getName();\n System.out.println(filename);\n if(filename==null || filename.trim().equals(\"\")){\n continue;\n }\n \/\/注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\\a\\b\\1.txt,而有些只是單純的文件名,如:1.txt\n \/\/處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分\n filename = filename.substring(filename.lastIndexOf(\"\\\\\")+1);\n \/\/獲取item中的上傳文件的輸入流\n InputStream in = item.getInputStream();\n \/\/創(chuàng)建一個文件輸出流\n FileOutputStream out = new FileOutputStream(savePath + \"\\\\\" + filename);\n \/\/創(chuàng)建一個緩沖區(qū)\n byte buffer[] = new byte[1024];\n \/\/判斷輸入流中的數(shù)據(jù)是否已經讀完的標識\n int len = 0;\n \/\/循環(huán)將輸入流讀入到緩沖區(qū)當中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù)\n while((len=in.read(buffer))>0){\n \/\/使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫入到指定的目錄(savePath + \"\\\\\" + filename)當中\(zhòng)n out.write(buffer, 0, len);\n }\n \/\/關閉輸入流\n in.close();\n \/\/關閉輸出流\n out.close();\n \/\/刪除處理文件上傳時生成的臨時文件\n item.delete();\n message = \"文件上傳成功!\";\n }\n }\n }catch (Exception e) {\n message= \"文件上傳失??!\";\n e.printStackTrace();\n \n }\n request.setAttribute(\"message\",message);\n request.getRequestDispatcher(\"\/message.jsp\").forward(request, response);\n }\n\n public void doPost(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n\n doGet(request, response);\n }\n}<\/pre>在Web.xml文件中注冊UploadHandleServlet<\/p>\n UploadHandleServlet<\/servlet-name>\n me.gacl.web.controller.UploadHandleServlet<\/servlet-class>\n<\/servlet>\n\n\n UploadHandleServlet<\/servlet-name>\n \/servlet\/UploadHandleServlet<\/url-pattern>\n<\/servlet-mapping><\/pre>文件上傳成功之后,上傳的文件保存在了WEB-INF目錄下的upload目錄,如下圖所示:<\/p>\n<\/p>"} Community Articles Topics Q&A Learn Course Programming Dictionary Tools Library Development tools Website Source Code PHP Libraries JS special effects Website Materials Extension plug-ins AI Tools Leisure Game Download Game Tutorials English 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup Home Java JavaBase How to upload files in java How to upload files in java angryTom Nov 12, 2019 am 11:57 AM java upload files 在Web應用系統(tǒng)開發(fā)中,文件上傳和下載功能是非常常用的功能,今天來講一下JavaWeb中的文件上傳功能的實現(xiàn)。 java怎么上傳文件 對于文件上傳,瀏覽器在上傳的過程中是將文件以流的形式提交到服務器端的,如果直接使用Servlet獲取上傳文件的輸入流然后再解析里面的請求參數(shù)是比較麻煩,所以一般選擇采用apache的開源工具common-fileupload這個文件上傳組件。這個common-fileupload上傳組件的jar包可以去apache官網(wǎng)上面下載,也可以在struts的lib文件夾下面找到,struts上傳的功能就是基于這個實現(xiàn)的。common-fileupload是依賴于common-io這個包的,所以還需要下載這個包。(推薦教程:java教程) 一、開發(fā)環(huán)境搭建 創(chuàng)建一個FileUploadAndDownLoad項目,加入Apache的commons-fileupload文件上傳組件的相關Jar包,如下圖所示: 二、實現(xiàn)文件上傳 2.1、文件上傳頁面和消息提示頁面 upload.jsp頁面的代碼如下:<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>文件上傳</title> </head> <body> <form action="${pageContext.request.contextPath}/servlet/UploadHandleServlet" enctype="multipart/form-data" method="post"> 上傳用戶:<input type="text" name="username"><br/> 上傳文件1:<input type="file" name="file1"><br/> 上傳文件2:<input type="file" name="file2"><br/> <input type="submit" value="提交"> </form> </body> </html>message.jsp的代碼如下:<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>消息提示</title> </head> <body> ${message} </body> </html>2.2、處理文件上傳的ServletUploadHandleServlet的代碼如下:package me.gacl.web.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadHandleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到上傳文件的保存目錄,將上傳的文件存放于WEB-INF目錄下,不允許外界直接訪問,保證上傳文件的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); //判斷上傳文件的保存目錄是否存在 if (!file.exists() && !file.isDirectory()) { System.out.println(savePath+"目錄不存在,需要創(chuàng)建"); //創(chuàng)建目錄 file.mkdir(); } //消息提示 String message = ""; try{ //使用Apache文件上傳組件處理文件上傳步驟: //1、創(chuàng)建一個DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //2、創(chuàng)建一個文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //3、判斷提交上來的數(shù)據(jù)是否是上傳表單的數(shù)據(jù) if(!ServletFileUpload.isMultipartContent(request)){ //按照傳統(tǒng)方式獲取數(shù)據(jù) return; } //4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //如果fileitem中封裝的是普通輸入項的數(shù)據(jù) if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項的數(shù)據(jù)的中文亂碼問題 String value = item.getString("UTF-8"); //value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); }else{//如果fileitem中封裝的是上傳文件 //得到上傳的文件名稱, String filename = item.getName(); System.out.println(filename); if(filename==null || filename.trim().equals("")){ continue; } //注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\")+1); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //創(chuàng)建一個文件輸出流 FileOutputStream out = new FileOutputStream(savePath + "\\" + filename); //創(chuàng)建一個緩沖區(qū) byte buffer[] = new byte[1024]; //判斷輸入流中的數(shù)據(jù)是否已經讀完的標識 int len = 0; //循環(huán)將輸入流讀入到緩沖區(qū)當中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù) while((len=in.read(buffer))>0){ //使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫入到指定的目錄(savePath + "\\" + filename)當中 out.write(buffer, 0, len); } //關閉輸入流 in.close(); //關閉輸出流 out.close(); //刪除處理文件上傳時生成的臨時文件 item.delete(); message = "文件上傳成功!"; } } }catch (Exception e) { message= "文件上傳失??!"; e.printStackTrace(); } request.setAttribute("message",message); request.getRequestDispatcher("/message.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }在Web.xml文件中注冊UploadHandleServlet<servlet> <servlet-name>UploadHandleServlet</servlet-name> <servlet-class>me.gacl.web.controller.UploadHandleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadHandleServlet</servlet-name> <url-pattern>/servlet/UploadHandleServlet</url-pattern> </servlet-mapping>文件上傳成功之后,上傳的文件保存在了WEB-INF目錄下的upload目錄,如下圖所示: The above is the detailed content of How to upload files in java. For more information, please follow other related articles on the PHP Chinese website! Statement of this Website The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn Hot AI Tools Undress AI Tool Undress images for free Undresser.AI Undress AI-powered app for creating realistic nude photos AI Clothes Remover Online AI tool for removing clothes from photos. Clothoff.io AI clothes remover Video Face Swap Swap faces in any video effortlessly with our completely free AI face swap tool! Show More Hot Article Grass Wonder Build Guide | Uma Musume Pretty Derby 3 weeks ago By Jack chen Roblox: 99 Nights In The Forest - All Badges And How To Unlock Them 3 weeks ago By DDD Uma Musume Pretty Derby Banner Schedule (July 2025) 4 weeks ago By Jack chen Today's Connections hint and answer 3rd July for 753 1 months ago By Jack chen Windows Security is blank or not showing options 4 weeks ago By 下次還敢 Show More Hot Tools Notepad++7.3.1 Easy-to-use and free code editor SublimeText3 Chinese version Chinese version, very easy to use Zend Studio 13.0.1 Powerful PHP integrated development environment Dreamweaver CS6 Visual web development tools SublimeText3 Mac version God-level code editing software (SublimeText3) Show More Hot Topics Laravel Tutorial 1597 29 PHP Tutorial 1488 72 Show More Related knowledge VSCode settings.json location Aug 01, 2025 am 06:12 AM The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory python itertools combinations example Jul 31, 2025 am 09:53 AM itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different; How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance. Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi python pytest fixture example Jul 31, 2025 am 09:35 AM fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests. Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized. How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear Advanced Spring Data JPA for Java Developers Jul 31, 2025 am 07:54 AM The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used See all articles
2.2、處理文件上傳的Servlet<\/p>
UploadHandleServlet的代碼如下:<\/p>
package me.gacl.web.controller;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.List;\nimport javax.servlet.ServletException;\nimport javax.servlet.http.HttpServlet;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\nimport org.apache.commons.fileupload.FileItem;\nimport org.apache.commons.fileupload.disk.DiskFileItemFactory;\nimport org.apache.commons.fileupload.servlet.ServletFileUpload;\n\npublic class UploadHandleServlet extends HttpServlet {\n\n public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n \/\/得到上傳文件的保存目錄,將上傳的文件存放于WEB-INF目錄下,不允許外界直接訪問,保證上傳文件的安全\n String savePath = this.getServletContext().getRealPath(\"\/WEB-INF\/upload\");\n File file = new File(savePath);\n \/\/判斷上傳文件的保存目錄是否存在\n if (!file.exists() && !file.isDirectory()) {\n System.out.println(savePath+\"目錄不存在,需要創(chuàng)建\");\n \/\/創(chuàng)建目錄\n file.mkdir();\n }\n \/\/消息提示\n String message = \"\";\n try{\n \/\/使用Apache文件上傳組件處理文件上傳步驟:\n \/\/1、創(chuàng)建一個DiskFileItemFactory工廠\n DiskFileItemFactory factory = new DiskFileItemFactory();\n \/\/2、創(chuàng)建一個文件上傳解析器\n ServletFileUpload upload = new ServletFileUpload(factory);\n \/\/解決上傳文件名的中文亂碼\n upload.setHeaderEncoding(\"UTF-8\"); \n \/\/3、判斷提交上來的數(shù)據(jù)是否是上傳表單的數(shù)據(jù)\n if(!ServletFileUpload.isMultipartContent(request)){\n \/\/按照傳統(tǒng)方式獲取數(shù)據(jù)\n return;\n }\n \/\/4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結果返回的是一個List集合,每一個FileItem對應一個Form表單的輸入項\n List list = upload.parseRequest(request);\n for(FileItem item : list){\n \/\/如果fileitem中封裝的是普通輸入項的數(shù)據(jù)\n if(item.isFormField()){\n String name = item.getFieldName();\n \/\/解決普通輸入項的數(shù)據(jù)的中文亂碼問題\n String value = item.getString(\"UTF-8\");\n \/\/value = new String(value.getBytes(\"iso8859-1\"),\"UTF-8\");\n System.out.println(name + \"=\" + value);\n }else{\/\/如果fileitem中封裝的是上傳文件\n \/\/得到上傳的文件名稱,\n String filename = item.getName();\n System.out.println(filename);\n if(filename==null || filename.trim().equals(\"\")){\n continue;\n }\n \/\/注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\\a\\b\\1.txt,而有些只是單純的文件名,如:1.txt\n \/\/處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分\n filename = filename.substring(filename.lastIndexOf(\"\\\\\")+1);\n \/\/獲取item中的上傳文件的輸入流\n InputStream in = item.getInputStream();\n \/\/創(chuàng)建一個文件輸出流\n FileOutputStream out = new FileOutputStream(savePath + \"\\\\\" + filename);\n \/\/創(chuàng)建一個緩沖區(qū)\n byte buffer[] = new byte[1024];\n \/\/判斷輸入流中的數(shù)據(jù)是否已經讀完的標識\n int len = 0;\n \/\/循環(huán)將輸入流讀入到緩沖區(qū)當中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù)\n while((len=in.read(buffer))>0){\n \/\/使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫入到指定的目錄(savePath + \"\\\\\" + filename)當中\(zhòng)n out.write(buffer, 0, len);\n }\n \/\/關閉輸入流\n in.close();\n \/\/關閉輸出流\n out.close();\n \/\/刪除處理文件上傳時生成的臨時文件\n item.delete();\n message = \"文件上傳成功!\";\n }\n }\n }catch (Exception e) {\n message= \"文件上傳失??!\";\n e.printStackTrace();\n \n }\n request.setAttribute(\"message\",message);\n request.getRequestDispatcher(\"\/message.jsp\").forward(request, response);\n }\n\n public void doPost(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n\n doGet(request, response);\n }\n}<\/pre>在Web.xml文件中注冊UploadHandleServlet<\/p>\n UploadHandleServlet<\/servlet-name>\n me.gacl.web.controller.UploadHandleServlet<\/servlet-class>\n<\/servlet>\n\n\n UploadHandleServlet<\/servlet-name>\n \/servlet\/UploadHandleServlet<\/url-pattern>\n<\/servlet-mapping><\/pre>文件上傳成功之后,上傳的文件保存在了WEB-INF目錄下的upload目錄,如下圖所示:<\/p>\n<\/p>"} Community Articles Topics Q&A Learn Course Programming Dictionary Tools Library Development tools Website Source Code PHP Libraries JS special effects Website Materials Extension plug-ins AI Tools Leisure Game Download Game Tutorials English 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup Home Java JavaBase How to upload files in java How to upload files in java angryTom Nov 12, 2019 am 11:57 AM java upload files 在Web應用系統(tǒng)開發(fā)中,文件上傳和下載功能是非常常用的功能,今天來講一下JavaWeb中的文件上傳功能的實現(xiàn)。 java怎么上傳文件 對于文件上傳,瀏覽器在上傳的過程中是將文件以流的形式提交到服務器端的,如果直接使用Servlet獲取上傳文件的輸入流然后再解析里面的請求參數(shù)是比較麻煩,所以一般選擇采用apache的開源工具common-fileupload這個文件上傳組件。這個common-fileupload上傳組件的jar包可以去apache官網(wǎng)上面下載,也可以在struts的lib文件夾下面找到,struts上傳的功能就是基于這個實現(xiàn)的。common-fileupload是依賴于common-io這個包的,所以還需要下載這個包。(推薦教程:java教程) 一、開發(fā)環(huán)境搭建 創(chuàng)建一個FileUploadAndDownLoad項目,加入Apache的commons-fileupload文件上傳組件的相關Jar包,如下圖所示: 二、實現(xiàn)文件上傳 2.1、文件上傳頁面和消息提示頁面 upload.jsp頁面的代碼如下:<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>文件上傳</title> </head> <body> <form action="${pageContext.request.contextPath}/servlet/UploadHandleServlet" enctype="multipart/form-data" method="post"> 上傳用戶:<input type="text" name="username"><br/> 上傳文件1:<input type="file" name="file1"><br/> 上傳文件2:<input type="file" name="file2"><br/> <input type="submit" value="提交"> </form> </body> </html>message.jsp的代碼如下:<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>消息提示</title> </head> <body> ${message} </body> </html>2.2、處理文件上傳的ServletUploadHandleServlet的代碼如下:package me.gacl.web.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadHandleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到上傳文件的保存目錄,將上傳的文件存放于WEB-INF目錄下,不允許外界直接訪問,保證上傳文件的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); //判斷上傳文件的保存目錄是否存在 if (!file.exists() && !file.isDirectory()) { System.out.println(savePath+"目錄不存在,需要創(chuàng)建"); //創(chuàng)建目錄 file.mkdir(); } //消息提示 String message = ""; try{ //使用Apache文件上傳組件處理文件上傳步驟: //1、創(chuàng)建一個DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //2、創(chuàng)建一個文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //3、判斷提交上來的數(shù)據(jù)是否是上傳表單的數(shù)據(jù) if(!ServletFileUpload.isMultipartContent(request)){ //按照傳統(tǒng)方式獲取數(shù)據(jù) return; } //4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //如果fileitem中封裝的是普通輸入項的數(shù)據(jù) if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項的數(shù)據(jù)的中文亂碼問題 String value = item.getString("UTF-8"); //value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); }else{//如果fileitem中封裝的是上傳文件 //得到上傳的文件名稱, String filename = item.getName(); System.out.println(filename); if(filename==null || filename.trim().equals("")){ continue; } //注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\")+1); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //創(chuàng)建一個文件輸出流 FileOutputStream out = new FileOutputStream(savePath + "\\" + filename); //創(chuàng)建一個緩沖區(qū) byte buffer[] = new byte[1024]; //判斷輸入流中的數(shù)據(jù)是否已經讀完的標識 int len = 0; //循環(huán)將輸入流讀入到緩沖區(qū)當中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù) while((len=in.read(buffer))>0){ //使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫入到指定的目錄(savePath + "\\" + filename)當中 out.write(buffer, 0, len); } //關閉輸入流 in.close(); //關閉輸出流 out.close(); //刪除處理文件上傳時生成的臨時文件 item.delete(); message = "文件上傳成功!"; } } }catch (Exception e) { message= "文件上傳失??!"; e.printStackTrace(); } request.setAttribute("message",message); request.getRequestDispatcher("/message.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }在Web.xml文件中注冊UploadHandleServlet<servlet> <servlet-name>UploadHandleServlet</servlet-name> <servlet-class>me.gacl.web.controller.UploadHandleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadHandleServlet</servlet-name> <url-pattern>/servlet/UploadHandleServlet</url-pattern> </servlet-mapping>文件上傳成功之后,上傳的文件保存在了WEB-INF目錄下的upload目錄,如下圖所示: The above is the detailed content of How to upload files in java. For more information, please follow other related articles on the PHP Chinese website! Statement of this Website The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn Hot AI Tools Undress AI Tool Undress images for free Undresser.AI Undress AI-powered app for creating realistic nude photos AI Clothes Remover Online AI tool for removing clothes from photos. Clothoff.io AI clothes remover Video Face Swap Swap faces in any video effortlessly with our completely free AI face swap tool! Show More Hot Article Grass Wonder Build Guide | Uma Musume Pretty Derby 3 weeks ago By Jack chen Roblox: 99 Nights In The Forest - All Badges And How To Unlock Them 3 weeks ago By DDD Uma Musume Pretty Derby Banner Schedule (July 2025) 4 weeks ago By Jack chen Today's Connections hint and answer 3rd July for 753 1 months ago By Jack chen Windows Security is blank or not showing options 4 weeks ago By 下次還敢 Show More Hot Tools Notepad++7.3.1 Easy-to-use and free code editor SublimeText3 Chinese version Chinese version, very easy to use Zend Studio 13.0.1 Powerful PHP integrated development environment Dreamweaver CS6 Visual web development tools SublimeText3 Mac version God-level code editing software (SublimeText3) Show More Hot Topics Laravel Tutorial 1597 29 PHP Tutorial 1488 72 Show More Related knowledge VSCode settings.json location Aug 01, 2025 am 06:12 AM The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory python itertools combinations example Jul 31, 2025 am 09:53 AM itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different; How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance. Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi python pytest fixture example Jul 31, 2025 am 09:35 AM fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests. Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized. How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear Advanced Spring Data JPA for Java Developers Jul 31, 2025 am 07:54 AM The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used See all articles
在Web.xml文件中注冊UploadHandleServlet<\/p>
\n UploadHandleServlet<\/servlet-name>\n me.gacl.web.controller.UploadHandleServlet<\/servlet-class>\n<\/servlet>\n\n\n UploadHandleServlet<\/servlet-name>\n \/servlet\/UploadHandleServlet<\/url-pattern>\n<\/servlet-mapping><\/pre>文件上傳成功之后,上傳的文件保存在了WEB-INF目錄下的upload目錄,如下圖所示:<\/p>\n<\/p>"} Community Articles Topics Q&A Learn Course Programming Dictionary Tools Library Development tools Website Source Code PHP Libraries JS special effects Website Materials Extension plug-ins AI Tools Leisure Game Download Game Tutorials English 簡體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup Home Java JavaBase How to upload files in java How to upload files in java angryTom Nov 12, 2019 am 11:57 AM java upload files 在Web應用系統(tǒng)開發(fā)中,文件上傳和下載功能是非常常用的功能,今天來講一下JavaWeb中的文件上傳功能的實現(xiàn)。 java怎么上傳文件 對于文件上傳,瀏覽器在上傳的過程中是將文件以流的形式提交到服務器端的,如果直接使用Servlet獲取上傳文件的輸入流然后再解析里面的請求參數(shù)是比較麻煩,所以一般選擇采用apache的開源工具common-fileupload這個文件上傳組件。這個common-fileupload上傳組件的jar包可以去apache官網(wǎng)上面下載,也可以在struts的lib文件夾下面找到,struts上傳的功能就是基于這個實現(xiàn)的。common-fileupload是依賴于common-io這個包的,所以還需要下載這個包。(推薦教程:java教程) 一、開發(fā)環(huán)境搭建 創(chuàng)建一個FileUploadAndDownLoad項目,加入Apache的commons-fileupload文件上傳組件的相關Jar包,如下圖所示: 二、實現(xiàn)文件上傳 2.1、文件上傳頁面和消息提示頁面 upload.jsp頁面的代碼如下:<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>文件上傳</title> </head> <body> <form action="${pageContext.request.contextPath}/servlet/UploadHandleServlet" enctype="multipart/form-data" method="post"> 上傳用戶:<input type="text" name="username"><br/> 上傳文件1:<input type="file" name="file1"><br/> 上傳文件2:<input type="file" name="file2"><br/> <input type="submit" value="提交"> </form> </body> </html>message.jsp的代碼如下:<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>消息提示</title> </head> <body> ${message} </body> </html>2.2、處理文件上傳的ServletUploadHandleServlet的代碼如下:package me.gacl.web.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadHandleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到上傳文件的保存目錄,將上傳的文件存放于WEB-INF目錄下,不允許外界直接訪問,保證上傳文件的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); //判斷上傳文件的保存目錄是否存在 if (!file.exists() && !file.isDirectory()) { System.out.println(savePath+"目錄不存在,需要創(chuàng)建"); //創(chuàng)建目錄 file.mkdir(); } //消息提示 String message = ""; try{ //使用Apache文件上傳組件處理文件上傳步驟: //1、創(chuàng)建一個DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //2、創(chuàng)建一個文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //3、判斷提交上來的數(shù)據(jù)是否是上傳表單的數(shù)據(jù) if(!ServletFileUpload.isMultipartContent(request)){ //按照傳統(tǒng)方式獲取數(shù)據(jù) return; } //4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //如果fileitem中封裝的是普通輸入項的數(shù)據(jù) if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項的數(shù)據(jù)的中文亂碼問題 String value = item.getString("UTF-8"); //value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); }else{//如果fileitem中封裝的是上傳文件 //得到上傳的文件名稱, String filename = item.getName(); System.out.println(filename); if(filename==null || filename.trim().equals("")){ continue; } //注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\")+1); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //創(chuàng)建一個文件輸出流 FileOutputStream out = new FileOutputStream(savePath + "\\" + filename); //創(chuàng)建一個緩沖區(qū) byte buffer[] = new byte[1024]; //判斷輸入流中的數(shù)據(jù)是否已經讀完的標識 int len = 0; //循環(huán)將輸入流讀入到緩沖區(qū)當中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù) while((len=in.read(buffer))>0){ //使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫入到指定的目錄(savePath + "\\" + filename)當中 out.write(buffer, 0, len); } //關閉輸入流 in.close(); //關閉輸出流 out.close(); //刪除處理文件上傳時生成的臨時文件 item.delete(); message = "文件上傳成功!"; } } }catch (Exception e) { message= "文件上傳失??!"; e.printStackTrace(); } request.setAttribute("message",message); request.getRequestDispatcher("/message.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }在Web.xml文件中注冊UploadHandleServlet<servlet> <servlet-name>UploadHandleServlet</servlet-name> <servlet-class>me.gacl.web.controller.UploadHandleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadHandleServlet</servlet-name> <url-pattern>/servlet/UploadHandleServlet</url-pattern> </servlet-mapping>文件上傳成功之后,上傳的文件保存在了WEB-INF目錄下的upload目錄,如下圖所示: The above is the detailed content of How to upload files in java. For more information, please follow other related articles on the PHP Chinese website! Statement of this Website The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn Hot AI Tools Undress AI Tool Undress images for free Undresser.AI Undress AI-powered app for creating realistic nude photos AI Clothes Remover Online AI tool for removing clothes from photos. Clothoff.io AI clothes remover Video Face Swap Swap faces in any video effortlessly with our completely free AI face swap tool! Show More Hot Article Grass Wonder Build Guide | Uma Musume Pretty Derby 3 weeks ago By Jack chen Roblox: 99 Nights In The Forest - All Badges And How To Unlock Them 3 weeks ago By DDD Uma Musume Pretty Derby Banner Schedule (July 2025) 4 weeks ago By Jack chen Today's Connections hint and answer 3rd July for 753 1 months ago By Jack chen Windows Security is blank or not showing options 4 weeks ago By 下次還敢 Show More Hot Tools Notepad++7.3.1 Easy-to-use and free code editor SublimeText3 Chinese version Chinese version, very easy to use Zend Studio 13.0.1 Powerful PHP integrated development environment Dreamweaver CS6 Visual web development tools SublimeText3 Mac version God-level code editing software (SublimeText3) Show More Hot Topics Laravel Tutorial 1597 29 PHP Tutorial 1488 72 Show More Related knowledge VSCode settings.json location Aug 01, 2025 am 06:12 AM The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory python itertools combinations example Jul 31, 2025 am 09:53 AM itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different; How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance. Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi python pytest fixture example Jul 31, 2025 am 09:35 AM fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests. Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized. How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear Advanced Spring Data JPA for Java Developers Jul 31, 2025 am 07:54 AM The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used See all articles
文件上傳成功之后,上傳的文件保存在了WEB-INF目錄下的upload目錄,如下圖所示:<\/p>\n
<\/p>"}
在Web應用系統(tǒng)開發(fā)中,文件上傳和下載功能是非常常用的功能,今天來講一下JavaWeb中的文件上傳功能的實現(xiàn)。
java怎么上傳文件
對于文件上傳,瀏覽器在上傳的過程中是將文件以流的形式提交到服務器端的,如果直接使用Servlet獲取上傳文件的輸入流然后再解析里面的請求參數(shù)是比較麻煩,所以一般選擇采用apache的開源工具common-fileupload這個文件上傳組件。這個common-fileupload上傳組件的jar包可以去apache官網(wǎng)上面下載,也可以在struts的lib文件夾下面找到,struts上傳的功能就是基于這個實現(xiàn)的。common-fileupload是依賴于common-io這個包的,所以還需要下載這個包。(推薦教程:java教程)
一、開發(fā)環(huán)境搭建
創(chuàng)建一個FileUploadAndDownLoad項目,加入Apache的commons-fileupload文件上傳組件的相關Jar包,如下圖所示:
二、實現(xiàn)文件上傳
2.1、文件上傳頁面和消息提示頁面
upload.jsp頁面的代碼如下:
<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>文件上傳</title> </head> <body> <form action="${pageContext.request.contextPath}/servlet/UploadHandleServlet" enctype="multipart/form-data" method="post"> 上傳用戶:<input type="text" name="username"><br/> 上傳文件1:<input type="file" name="file1"><br/> 上傳文件2:<input type="file" name="file2"><br/> <input type="submit" value="提交"> </form> </body> </html>
message.jsp的代碼如下:
<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>消息提示</title> </head> <body> ${message} </body> </html>
2.2、處理文件上傳的Servlet
UploadHandleServlet的代碼如下:
package me.gacl.web.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadHandleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到上傳文件的保存目錄,將上傳的文件存放于WEB-INF目錄下,不允許外界直接訪問,保證上傳文件的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); //判斷上傳文件的保存目錄是否存在 if (!file.exists() && !file.isDirectory()) { System.out.println(savePath+"目錄不存在,需要創(chuàng)建"); //創(chuàng)建目錄 file.mkdir(); } //消息提示 String message = ""; try{ //使用Apache文件上傳組件處理文件上傳步驟: //1、創(chuàng)建一個DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //2、創(chuàng)建一個文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //3、判斷提交上來的數(shù)據(jù)是否是上傳表單的數(shù)據(jù) if(!ServletFileUpload.isMultipartContent(request)){ //按照傳統(tǒng)方式獲取數(shù)據(jù) return; } //4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //如果fileitem中封裝的是普通輸入項的數(shù)據(jù) if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項的數(shù)據(jù)的中文亂碼問題 String value = item.getString("UTF-8"); //value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); }else{//如果fileitem中封裝的是上傳文件 //得到上傳的文件名稱, String filename = item.getName(); System.out.println(filename); if(filename==null || filename.trim().equals("")){ continue; } //注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\")+1); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //創(chuàng)建一個文件輸出流 FileOutputStream out = new FileOutputStream(savePath + "\\" + filename); //創(chuàng)建一個緩沖區(qū) byte buffer[] = new byte[1024]; //判斷輸入流中的數(shù)據(jù)是否已經讀完的標識 int len = 0; //循環(huán)將輸入流讀入到緩沖區(qū)當中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù) while((len=in.read(buffer))>0){ //使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫入到指定的目錄(savePath + "\\" + filename)當中 out.write(buffer, 0, len); } //關閉輸入流 in.close(); //關閉輸出流 out.close(); //刪除處理文件上傳時生成的臨時文件 item.delete(); message = "文件上傳成功!"; } } }catch (Exception e) { message= "文件上傳失??!"; e.printStackTrace(); } request.setAttribute("message",message); request.getRequestDispatcher("/message.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
在Web.xml文件中注冊UploadHandleServlet
<servlet> <servlet-name>UploadHandleServlet</servlet-name> <servlet-class>me.gacl.web.controller.UploadHandleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadHandleServlet</servlet-name> <url-pattern>/servlet/UploadHandleServlet</url-pattern> </servlet-mapping>
文件上傳成功之后,上傳的文件保存在了WEB-INF目錄下的upload目錄,如下圖所示:
The above is the detailed content of How to upload files in java. For more information, please follow other related articles on the PHP Chinese website!
Undress images for free
AI-powered app for creating realistic nude photos
Online AI tool for removing clothes from photos.
AI clothes remover
Swap faces in any video effortlessly with our completely free AI face swap tool!
Easy-to-use and free code editor
Chinese version, very easy to use
Powerful PHP integrated development environment
Visual web development tools
God-level code editing software (SublimeText3)
The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory
itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;
To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.
DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi
fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.
java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.
Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear
The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used