java基于servlet實現(xiàn)文件上傳功能
本文實例為大家分享了java基于servlet實現(xiàn)文件上傳的具體代碼,供大家參考,具體內(nèi)容如下
研究了一天終于將java上傳文件看懂了,當(dāng)然懂的僅僅是皮毛,不妨記下來防止以后忘了。
我們在網(wǎng)上看關(guān)于文件的上傳有很多的介紹,當(dāng)然有的可以使用有的則不合適:我們首先來看前臺的界面。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>上傳文件</title> <link href="../css/bootstrap.min.css" rel="stylesheet"> <script src="../js/jquery.min.js"></script> <script src="../js/bootstrap.min.js" type="text/javascript"></script> </head> <body> <div class="container kv-main"> <div class="page-header"> <h1>上傳文件</h1> </div> <form enctype="multipart/form-data" action="../upload?method=uploadPic" method="post"> <input name="file-1" type="file"><br> <button type="submit" class="btn btn-primary">Submit</button> <button type="reset" class="btn btn-default">Reset</button> </form> <hr> <br> </div> </body> </html>
這個地方是為了好看使用了Bootstrap進行布局,如下:

在做好前臺的頁面之后,我們開看后臺的代碼,在看servlet之前我們首先來看看web.xml的配置:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>myShop</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>upload</servlet-name> <servlet-class>com.epoint.shop.fileupload.UpLoadServlet</servlet-class> <init-param> <param-name>filePath</param-name> <param-value>E://workspace1/myShop/WebContent/upload</param-value> </init-param> <init-param> <param-name>tempFilePath</param-name> <param-value>temp</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>upload</servlet-name> <url-pattern>/upload</url-pattern> </servlet-mapping> </web-app>
為什么要配置web.xml,是因為我們在servlet有一個要獲取文件存放的路徑,我們不妨將這個路徑存放到web.xml這個我們當(dāng)我們的項目進行平臺的遷移的時候,我們需要改動的只是web.xml不需要給java內(nèi)部的核心的代碼。
然后我們來看servlet的代碼:
package com.epoint.shop.fileupload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
@WebServlet("/UpLoad")
public class UpLoadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String TEMP_FOLDER="/upload";
// 上傳配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
private String filePath; //存放上傳文件的目錄
private String tempFilePath; //存放臨時文件的目錄
public UpLoadServlet() {
super();
}
public void init(ServletConfig config)throws ServletException {
super.init(config);
filePath=config.getInitParameter("filePath");
System.out.println(filePath);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String methodName=request.getParameter("method");
if(methodName!=null){
try {
Method method=this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
method.invoke(this, request,response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void uploadPic(HttpServletRequest request, HttpServletResponse response) throws Exception{
//檢測是否為多媒體上傳
if(!ServletFileUpload.isMultipartContent(request)){
//如果不是就停止
PrintWriter writer=response.getWriter();
writer.println("表單中必須包含enctype=multipart/form-data");
writer.flush();
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory(); // 創(chuàng)建文件項目工廠對象
factory.setRepository(new File(savePath)); //設(shè)置臨時文件夾為TEMP_FOLDER
factory.setSizeThreshold(1024 * 1024); // 設(shè)置緩沖區(qū)大小為 1M
// 構(gòu)造臨時路徑來存儲上傳的文件
ServletFileUpload upload = new ServletFileUpload(factory);//用工廠實例化上傳組件,ServletFileUpload用來解析文件上傳請求
// 設(shè)置最大文件上傳值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 設(shè)置最大請求值 (包含文件和表單數(shù)據(jù))
upload.setSizeMax(MAX_REQUEST_SIZE);
upload.setHeaderEncoding("UTF-8");
@SuppressWarnings("unchecked")
List<FileItem> list = upload.parseRequest(request);
if (list != null && list.size() > 0) {
for (FileItem item : list) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
File storeFile = new File(filePath,fileName);
// 保存文件到硬盤
item.write(storeFile);
request.setAttribute("message","文件上傳成功!");
}
}
}
}
}
在今天上午我在編寫的過程中遇到一個問題,就是有一個
List<FileItem> list = upload.parseRequest(request);
就這個代碼獲取到的list一直為空,如果你也遇到這樣的問題,可以配置一下web.xml,因為我們tomcat可能會對文件進行攔截,但是我也不清楚為什么在配置了web.xml之后,就可以上傳文件了。你如果遇到這樣的問題不妨是試一試,請求通過web.xml的mapping進行轉(zhuǎn)發(fā)。
還有文件的上傳需要兩個包,別忘了

上面畫圓圈的就是了,希望對你有所幫助。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
KafkaListener注解的實現(xiàn)機制源碼解析
這篇文章主要為大家介紹了KafkaListener注解的實現(xiàn)機制源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10
Java實現(xiàn)將Object轉(zhuǎn)成List的五種方法
在Java中,將一個Object轉(zhuǎn)換為List是一個常見的需求,尤其是在處理集合操作和數(shù)據(jù)轉(zhuǎn)換時,本文將詳細討論如何實現(xiàn)這一轉(zhuǎn)換,并提供一些代碼示例,需要的朋友可以參考下2025-03-03
深入理解JavaWeb中過濾器與監(jiān)聽器的應(yīng)用
這篇文章主要介紹了JavaWeb中過濾器與監(jiān)聽器的應(yīng)用,過濾器能夠?qū)ζヅ涞恼埱蟮竭_目標(biāo)之前或返回響應(yīng)之后增加一些處理代碼,監(jiān)聽器是一個接口內(nèi)容由我們實現(xiàn),會在特定時間被調(diào)用,感興趣想要詳細了解可以參考下文2023-05-05

