message.jsp的代碼如下:<\/p>
<%@ page language=\"java\" pageEncoding=\"UTF-8\"%>\n\n\n \n 消息提示<\/title>\n <\/head>\n \n 国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂\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目錄下,不允許外界直接訪問(wèn),保證上傳文件的安全\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+\"目錄不存在,需要?jiǎng)?chuàng)建\");\n \/\/創(chuàng)建目錄\n file.mkdir();\n }\n \/\/消息提示\n String message = \"\";\n try{\n \/\/使用Apache文件上傳組件處理文件上傳步驟:\n \/\/1、創(chuàng)建一個(gè)DiskFileItemFactory工廠\n DiskFileItemFactory factory = new DiskFileItemFactory();\n \/\/2、創(chuàng)建一個(gè)文件上傳解析器\n ServletFileUpload upload = new ServletFileUpload(factory);\n \/\/解決上傳文件名的中文亂碼\n upload.setHeaderEncoding(\"UTF-8\"); \n \/\/3、判斷提交上來(lái)的數(shù)據(jù)是否是上傳表單的數(shù)據(jù)\n if(!ServletFileUpload.isMultipartContent(request)){\n \/\/按照傳統(tǒng)方式獲取數(shù)據(jù)\n return;\n }\n \/\/4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個(gè)List集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng)\n List list = upload.parseRequest(request);\n for(FileItem item : list){\n \/\/如果fileitem中封裝的是普通輸入項(xiàng)的數(shù)據(jù)\n if(item.isFormField()){\n String name = item.getFieldName();\n \/\/解決普通輸入項(xiàng)的數(shù)據(jù)的中文亂碼問(wèn)題\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 \/\/注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來(lái)的文件名是帶有路徑的,如: 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)建一個(gè)文件輸出流\n FileOutputStream out = new FileOutputStream(savePath + \"\\\\\" + filename);\n \/\/創(chuàng)建一個(gè)緩沖區(qū)\n byte buffer[] = new byte[1024];\n \/\/判斷輸入流中的數(shù)據(jù)是否已經(jīng)讀完的標(biāo)識(shí)\n int len = 0;\n \/\/循環(huán)將輸入流讀入到緩沖區(qū)當(dāng)中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù)\n while((len=in.read(buffer))>0){\n \/\/使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫(xiě)入到指定的目錄(savePath + \"\\\\\" + filename)當(dāng)中\(zhòng)n out.write(buffer, 0, len);\n }\n \/\/關(guān)閉輸入流\n in.close();\n \/\/關(guān)閉輸出流\n out.close();\n \/\/刪除處理文件上傳時(shí)生成的臨時(shí)文件\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文件中注冊(cè)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 簡(jiǎn)體中文 English 繁體中文 日本語(yǔ) ??? 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應(yīng)用系統(tǒng)開(kāi)發(fā)中,文件上傳和下載功能是非常常用的功能,今天來(lái)講一下JavaWeb中的文件上傳功能的實(shí)現(xiàn)。 java怎么上傳文件 對(duì)于文件上傳,瀏覽器在上傳的過(guò)程中是將文件以流的形式提交到服務(wù)器端的,如果直接使用Servlet獲取上傳文件的輸入流然后再解析里面的請(qǐng)求參數(shù)是比較麻煩,所以一般選擇采用apache的開(kāi)源工具common-fileupload這個(gè)文件上傳組件。這個(gè)common-fileupload上傳組件的jar包可以去apache官網(wǎng)上面下載,也可以在struts的lib文件夾下面找到,struts上傳的功能就是基于這個(gè)實(shí)現(xiàn)的。common-fileupload是依賴于common-io這個(gè)包的,所以還需要下載這個(gè)包。(推薦教程:java教程) 一、開(kāi)發(fā)環(huán)境搭建 創(chuàng)建一個(gè)FileUploadAndDownLoad項(xiàng)目,加入Apache的commons-fileupload文件上傳組件的相關(guān)Jar包,如下圖所示: 二、實(shí)現(xiàn)文件上傳 2.1、文件上傳頁(yè)面和消息提示頁(yè)面 upload.jsp頁(yè)面的代碼如下:<%@ 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目錄下,不允許外界直接訪問(wèn),保證上傳文件的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); //判斷上傳文件的保存目錄是否存在 if (!file.exists() && !file.isDirectory()) { System.out.println(savePath+"目錄不存在,需要?jiǎng)?chuàng)建"); //創(chuàng)建目錄 file.mkdir(); } //消息提示 String message = ""; try{ //使用Apache文件上傳組件處理文件上傳步驟: //1、創(chuàng)建一個(gè)DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //2、創(chuàng)建一個(gè)文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //3、判斷提交上來(lái)的數(shù)據(jù)是否是上傳表單的數(shù)據(jù) if(!ServletFileUpload.isMultipartContent(request)){ //按照傳統(tǒng)方式獲取數(shù)據(jù) return; } //4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個(gè)List<FileItem>集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng) List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //如果fileitem中封裝的是普通輸入項(xiàng)的數(shù)據(jù) if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項(xiàng)的數(shù)據(jù)的中文亂碼問(wèn)題 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; } //注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來(lái)的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\")+1); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //創(chuàng)建一個(gè)文件輸出流 FileOutputStream out = new FileOutputStream(savePath + "\\" + filename); //創(chuàng)建一個(gè)緩沖區(qū) byte buffer[] = new byte[1024]; //判斷輸入流中的數(shù)據(jù)是否已經(jīng)讀完的標(biāo)識(shí) int len = 0; //循環(huán)將輸入流讀入到緩沖區(qū)當(dāng)中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù) while((len=in.read(buffer))>0){ //使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫(xiě)入到指定的目錄(savePath + "\\" + filename)當(dāng)中 out.write(buffer, 0, len); } //關(guān)閉輸入流 in.close(); //關(guān)閉輸出流 out.close(); //刪除處理文件上傳時(shí)生成的臨時(shí)文件 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文件中注冊(cè)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 1 months ago By Jack chen Roblox: 99 Nights In The Forest - All Badges And How To Unlock Them 4 weeks ago By DDD Uma Musume Pretty Derby Banner Schedule (July 2025) 1 months ago By Jack chen RimWorld Odyssey Temperature Guide for Ships and Gravtech 3 weeks ago By Jack chen Windows Security is blank or not showing options 1 months 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 1601 29 PHP Tutorial 1502 276 Show More Related knowledge 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. 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 Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste, Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac go by example defer statement explained Aug 02, 2025 am 06:26 AM defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability. Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label. 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目錄下,不允許外界直接訪問(wèn),保證上傳文件的安全\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+\"目錄不存在,需要?jiǎng)?chuàng)建\");\n \/\/創(chuàng)建目錄\n file.mkdir();\n }\n \/\/消息提示\n String message = \"\";\n try{\n \/\/使用Apache文件上傳組件處理文件上傳步驟:\n \/\/1、創(chuàng)建一個(gè)DiskFileItemFactory工廠\n DiskFileItemFactory factory = new DiskFileItemFactory();\n \/\/2、創(chuàng)建一個(gè)文件上傳解析器\n ServletFileUpload upload = new ServletFileUpload(factory);\n \/\/解決上傳文件名的中文亂碼\n upload.setHeaderEncoding(\"UTF-8\"); \n \/\/3、判斷提交上來(lái)的數(shù)據(jù)是否是上傳表單的數(shù)據(jù)\n if(!ServletFileUpload.isMultipartContent(request)){\n \/\/按照傳統(tǒng)方式獲取數(shù)據(jù)\n return;\n }\n \/\/4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個(gè)List集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng)\n List list = upload.parseRequest(request);\n for(FileItem item : list){\n \/\/如果fileitem中封裝的是普通輸入項(xiàng)的數(shù)據(jù)\n if(item.isFormField()){\n String name = item.getFieldName();\n \/\/解決普通輸入項(xiàng)的數(shù)據(jù)的中文亂碼問(wèn)題\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 \/\/注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來(lái)的文件名是帶有路徑的,如: 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)建一個(gè)文件輸出流\n FileOutputStream out = new FileOutputStream(savePath + \"\\\\\" + filename);\n \/\/創(chuàng)建一個(gè)緩沖區(qū)\n byte buffer[] = new byte[1024];\n \/\/判斷輸入流中的數(shù)據(jù)是否已經(jīng)讀完的標(biāo)識(shí)\n int len = 0;\n \/\/循環(huán)將輸入流讀入到緩沖區(qū)當(dāng)中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù)\n while((len=in.read(buffer))>0){\n \/\/使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫(xiě)入到指定的目錄(savePath + \"\\\\\" + filename)當(dāng)中\(zhòng)n out.write(buffer, 0, len);\n }\n \/\/關(guān)閉輸入流\n in.close();\n \/\/關(guān)閉輸出流\n out.close();\n \/\/刪除處理文件上傳時(shí)生成的臨時(shí)文件\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文件中注冊(cè)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 簡(jiǎn)體中文 English 繁體中文 日本語(yǔ) ??? 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應(yīng)用系統(tǒng)開(kāi)發(fā)中,文件上傳和下載功能是非常常用的功能,今天來(lái)講一下JavaWeb中的文件上傳功能的實(shí)現(xiàn)。 java怎么上傳文件 對(duì)于文件上傳,瀏覽器在上傳的過(guò)程中是將文件以流的形式提交到服務(wù)器端的,如果直接使用Servlet獲取上傳文件的輸入流然后再解析里面的請(qǐng)求參數(shù)是比較麻煩,所以一般選擇采用apache的開(kāi)源工具common-fileupload這個(gè)文件上傳組件。這個(gè)common-fileupload上傳組件的jar包可以去apache官網(wǎng)上面下載,也可以在struts的lib文件夾下面找到,struts上傳的功能就是基于這個(gè)實(shí)現(xiàn)的。common-fileupload是依賴于common-io這個(gè)包的,所以還需要下載這個(gè)包。(推薦教程:java教程) 一、開(kāi)發(fā)環(huán)境搭建 創(chuàng)建一個(gè)FileUploadAndDownLoad項(xiàng)目,加入Apache的commons-fileupload文件上傳組件的相關(guān)Jar包,如下圖所示: 二、實(shí)現(xiàn)文件上傳 2.1、文件上傳頁(yè)面和消息提示頁(yè)面 upload.jsp頁(yè)面的代碼如下:<%@ 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目錄下,不允許外界直接訪問(wèn),保證上傳文件的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); //判斷上傳文件的保存目錄是否存在 if (!file.exists() && !file.isDirectory()) { System.out.println(savePath+"目錄不存在,需要?jiǎng)?chuàng)建"); //創(chuàng)建目錄 file.mkdir(); } //消息提示 String message = ""; try{ //使用Apache文件上傳組件處理文件上傳步驟: //1、創(chuàng)建一個(gè)DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //2、創(chuàng)建一個(gè)文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //3、判斷提交上來(lái)的數(shù)據(jù)是否是上傳表單的數(shù)據(jù) if(!ServletFileUpload.isMultipartContent(request)){ //按照傳統(tǒng)方式獲取數(shù)據(jù) return; } //4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個(gè)List<FileItem>集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng) List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //如果fileitem中封裝的是普通輸入項(xiàng)的數(shù)據(jù) if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項(xiàng)的數(shù)據(jù)的中文亂碼問(wèn)題 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; } //注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來(lái)的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\")+1); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //創(chuàng)建一個(gè)文件輸出流 FileOutputStream out = new FileOutputStream(savePath + "\\" + filename); //創(chuàng)建一個(gè)緩沖區(qū) byte buffer[] = new byte[1024]; //判斷輸入流中的數(shù)據(jù)是否已經(jīng)讀完的標(biāo)識(shí) int len = 0; //循環(huán)將輸入流讀入到緩沖區(qū)當(dāng)中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù) while((len=in.read(buffer))>0){ //使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫(xiě)入到指定的目錄(savePath + "\\" + filename)當(dāng)中 out.write(buffer, 0, len); } //關(guān)閉輸入流 in.close(); //關(guān)閉輸出流 out.close(); //刪除處理文件上傳時(shí)生成的臨時(shí)文件 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文件中注冊(cè)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 1 months ago By Jack chen Roblox: 99 Nights In The Forest - All Badges And How To Unlock Them 4 weeks ago By DDD Uma Musume Pretty Derby Banner Schedule (July 2025) 1 months ago By Jack chen RimWorld Odyssey Temperature Guide for Ships and Gravtech 3 weeks ago By Jack chen Windows Security is blank or not showing options 1 months 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 1601 29 PHP Tutorial 1502 276 Show More Related knowledge 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. 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 Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste, Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac go by example defer statement explained Aug 02, 2025 am 06:26 AM defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability. Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label. See all articles
在Web.xml文件中注冊(cè)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 簡(jiǎn)體中文 English 繁體中文 日本語(yǔ) ??? 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應(yīng)用系統(tǒng)開(kāi)發(fā)中,文件上傳和下載功能是非常常用的功能,今天來(lái)講一下JavaWeb中的文件上傳功能的實(shí)現(xiàn)。 java怎么上傳文件 對(duì)于文件上傳,瀏覽器在上傳的過(guò)程中是將文件以流的形式提交到服務(wù)器端的,如果直接使用Servlet獲取上傳文件的輸入流然后再解析里面的請(qǐng)求參數(shù)是比較麻煩,所以一般選擇采用apache的開(kāi)源工具common-fileupload這個(gè)文件上傳組件。這個(gè)common-fileupload上傳組件的jar包可以去apache官網(wǎng)上面下載,也可以在struts的lib文件夾下面找到,struts上傳的功能就是基于這個(gè)實(shí)現(xiàn)的。common-fileupload是依賴于common-io這個(gè)包的,所以還需要下載這個(gè)包。(推薦教程:java教程) 一、開(kāi)發(fā)環(huán)境搭建 創(chuàng)建一個(gè)FileUploadAndDownLoad項(xiàng)目,加入Apache的commons-fileupload文件上傳組件的相關(guān)Jar包,如下圖所示: 二、實(shí)現(xiàn)文件上傳 2.1、文件上傳頁(yè)面和消息提示頁(yè)面 upload.jsp頁(yè)面的代碼如下:<%@ 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目錄下,不允許外界直接訪問(wèn),保證上傳文件的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); //判斷上傳文件的保存目錄是否存在 if (!file.exists() && !file.isDirectory()) { System.out.println(savePath+"目錄不存在,需要?jiǎng)?chuàng)建"); //創(chuàng)建目錄 file.mkdir(); } //消息提示 String message = ""; try{ //使用Apache文件上傳組件處理文件上傳步驟: //1、創(chuàng)建一個(gè)DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //2、創(chuàng)建一個(gè)文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //3、判斷提交上來(lái)的數(shù)據(jù)是否是上傳表單的數(shù)據(jù) if(!ServletFileUpload.isMultipartContent(request)){ //按照傳統(tǒng)方式獲取數(shù)據(jù) return; } //4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個(gè)List<FileItem>集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng) List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //如果fileitem中封裝的是普通輸入項(xiàng)的數(shù)據(jù) if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項(xiàng)的數(shù)據(jù)的中文亂碼問(wèn)題 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; } //注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來(lái)的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\")+1); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //創(chuàng)建一個(gè)文件輸出流 FileOutputStream out = new FileOutputStream(savePath + "\\" + filename); //創(chuàng)建一個(gè)緩沖區(qū) byte buffer[] = new byte[1024]; //判斷輸入流中的數(shù)據(jù)是否已經(jīng)讀完的標(biāo)識(shí) int len = 0; //循環(huán)將輸入流讀入到緩沖區(qū)當(dāng)中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù) while((len=in.read(buffer))>0){ //使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫(xiě)入到指定的目錄(savePath + "\\" + filename)當(dāng)中 out.write(buffer, 0, len); } //關(guān)閉輸入流 in.close(); //關(guān)閉輸出流 out.close(); //刪除處理文件上傳時(shí)生成的臨時(shí)文件 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文件中注冊(cè)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 1 months ago By Jack chen Roblox: 99 Nights In The Forest - All Badges And How To Unlock Them 4 weeks ago By DDD Uma Musume Pretty Derby Banner Schedule (July 2025) 1 months ago By Jack chen RimWorld Odyssey Temperature Guide for Ships and Gravtech 3 weeks ago By Jack chen Windows Security is blank or not showing options 1 months 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 1601 29 PHP Tutorial 1502 276 Show More Related knowledge 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. 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 Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste, Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac go by example defer statement explained Aug 02, 2025 am 06:26 AM defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability. Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label. See all articles
文件上傳成功之后,上傳的文件保存在了WEB-INF目錄下的upload目錄,如下圖所示:<\/p>\n
<\/p>"}
在Web應(yīng)用系統(tǒng)開(kāi)發(fā)中,文件上傳和下載功能是非常常用的功能,今天來(lái)講一下JavaWeb中的文件上傳功能的實(shí)現(xiàn)。
java怎么上傳文件
對(duì)于文件上傳,瀏覽器在上傳的過(guò)程中是將文件以流的形式提交到服務(wù)器端的,如果直接使用Servlet獲取上傳文件的輸入流然后再解析里面的請(qǐng)求參數(shù)是比較麻煩,所以一般選擇采用apache的開(kāi)源工具common-fileupload這個(gè)文件上傳組件。這個(gè)common-fileupload上傳組件的jar包可以去apache官網(wǎng)上面下載,也可以在struts的lib文件夾下面找到,struts上傳的功能就是基于這個(gè)實(shí)現(xiàn)的。common-fileupload是依賴于common-io這個(gè)包的,所以還需要下載這個(gè)包。(推薦教程:java教程)
一、開(kāi)發(fā)環(huán)境搭建
創(chuàng)建一個(gè)FileUploadAndDownLoad項(xiàng)目,加入Apache的commons-fileupload文件上傳組件的相關(guān)Jar包,如下圖所示:
二、實(shí)現(xiàn)文件上傳
2.1、文件上傳頁(yè)面和消息提示頁(yè)面
upload.jsp頁(yè)面的代碼如下:
<%@ 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目錄下,不允許外界直接訪問(wèn),保證上傳文件的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); //判斷上傳文件的保存目錄是否存在 if (!file.exists() && !file.isDirectory()) { System.out.println(savePath+"目錄不存在,需要?jiǎng)?chuàng)建"); //創(chuàng)建目錄 file.mkdir(); } //消息提示 String message = ""; try{ //使用Apache文件上傳組件處理文件上傳步驟: //1、創(chuàng)建一個(gè)DiskFileItemFactory工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); //2、創(chuàng)建一個(gè)文件上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //解決上傳文件名的中文亂碼 upload.setHeaderEncoding("UTF-8"); //3、判斷提交上來(lái)的數(shù)據(jù)是否是上傳表單的數(shù)據(jù) if(!ServletFileUpload.isMultipartContent(request)){ //按照傳統(tǒng)方式獲取數(shù)據(jù) return; } //4、使用ServletFileUpload解析器解析上傳數(shù)據(jù),解析結(jié)果返回的是一個(gè)List<FileItem>集合,每一個(gè)FileItem對(duì)應(yīng)一個(gè)Form表單的輸入項(xiàng) List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //如果fileitem中封裝的是普通輸入項(xiàng)的數(shù)據(jù) if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項(xiàng)的數(shù)據(jù)的中文亂碼問(wèn)題 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; } //注意:不同的瀏覽器提交的文件名是不一樣的,有些瀏覽器提交上來(lái)的文件名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的文件名,如:1.txt //處理獲取到的上傳文件的文件名的路徑部分,只保留文件名部分 filename = filename.substring(filename.lastIndexOf("\\")+1); //獲取item中的上傳文件的輸入流 InputStream in = item.getInputStream(); //創(chuàng)建一個(gè)文件輸出流 FileOutputStream out = new FileOutputStream(savePath + "\\" + filename); //創(chuàng)建一個(gè)緩沖區(qū) byte buffer[] = new byte[1024]; //判斷輸入流中的數(shù)據(jù)是否已經(jīng)讀完的標(biāo)識(shí) int len = 0; //循環(huán)將輸入流讀入到緩沖區(qū)當(dāng)中,(len=in.read(buffer))>0就表示in里面還有數(shù)據(jù) while((len=in.read(buffer))>0){ //使用FileOutputStream輸出流將緩沖區(qū)的數(shù)據(jù)寫(xiě)入到指定的目錄(savePath + "\\" + filename)當(dāng)中 out.write(buffer, 0, len); } //關(guān)閉輸入流 in.close(); //關(guān)閉輸出流 out.close(); //刪除處理文件上傳時(shí)生成的臨時(shí)文件 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文件中注冊(cè)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)
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.
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
Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,
Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c
Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces
Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac
defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.
Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.