java基于servlet實(shí)現(xiàn)文件上傳功能
本文實(shí)例為大家分享了java基于servlet實(shí)現(xiàn)文件上傳的具體代碼,供大家參考,具體內(nèi)容如下
研究了一天終于將java上傳文件看懂了,當(dāng)然懂的僅僅是皮毛,不妨記下來防止以后忘了。
我們?cè)诰W(wǎng)上看關(guān)于文件的上傳有很多的介紹,當(dāng)然有的可以使用有的則不合適:我們首先來看前臺(tái)的界面。
<!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>
這個(gè)地方是為了好看使用了Bootstrap進(jìn)行布局,如下:

在做好前臺(tái)的頁面之后,我們開看后臺(tái)的代碼,在看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,是因?yàn)槲覀冊(cè)趕ervlet有一個(gè)要獲取文件存放的路徑,我們不妨將這個(gè)路徑存放到web.xml這個(gè)我們當(dāng)我們的項(xiàng)目進(jìn)行平臺(tái)的遷移的時(shí)候,我們需要改動(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; //存放臨時(shí)文件的目錄
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{
//檢測(cè)是否為多媒體上傳
if(!ServletFileUpload.isMultipartContent(request)){
//如果不是就停止
PrintWriter writer=response.getWriter();
writer.println("表單中必須包含enctype=multipart/form-data");
writer.flush();
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory(); // 創(chuàng)建文件項(xiàng)目工廠對(duì)象
factory.setRepository(new File(savePath)); //設(shè)置臨時(shí)文件夾為TEMP_FOLDER
factory.setSizeThreshold(1024 * 1024); // 設(shè)置緩沖區(qū)大小為 1M
// 構(gòu)造臨時(shí)路徑來存儲(chǔ)上傳的文件
ServletFileUpload upload = new ServletFileUpload(factory);//用工廠實(shí)例化上傳組件,ServletFileUpload用來解析文件上傳請(qǐng)求
// 設(shè)置最大文件上傳值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 設(shè)置最大請(qǐng)求值 (包含文件和表單數(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","文件上傳成功!");
}
}
}
}
}
在今天上午我在編寫的過程中遇到一個(gè)問題,就是有一個(gè)
List<FileItem> list = upload.parseRequest(request);
就這個(gè)代碼獲取到的list一直為空,如果你也遇到這樣的問題,可以配置一下web.xml,因?yàn)槲覀僼omcat可能會(huì)對(duì)文件進(jìn)行攔截,但是我也不清楚為什么在配置了web.xml之后,就可以上傳文件了。你如果遇到這樣的問題不妨是試一試,請(qǐng)求通過web.xml的mapping進(jìn)行轉(zhuǎn)發(fā)。
還有文件的上傳需要兩個(gè)包,別忘了

上面畫圓圈的就是了,希望對(duì)你有所幫助。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java基于ServletContextListener實(shí)現(xiàn)UDP監(jiān)聽
- JavaWeb項(xiàng)目Servlet無法訪問問題解決
- 使用Java servlet實(shí)現(xiàn)自動(dòng)登錄退出功能
- Java service層獲取HttpServletRequest工具類的方法
- IDEA新建javaWeb以及Servlet簡(jiǎn)單實(shí)現(xiàn)小結(jié)
- java通過HttpServletRequest獲取post請(qǐng)求中的body內(nèi)容的方法
- Java servlet 使用 PrintWriter 時(shí)的編碼與亂碼的示例代碼
- Java ServletContext對(duì)象原理及功能解析
相關(guān)文章
詳解MyBatis中主鍵回填的兩種實(shí)現(xiàn)方式
這篇文章主要介紹了詳解MyBatis中主鍵回填的兩種實(shí)現(xiàn)方式,主鍵回填其實(shí)是一個(gè)非常常見的需求,特別是在數(shù)據(jù)添加的過程中,我們經(jīng)常需要添加完數(shù)據(jù)之后,需要獲取剛剛添加的數(shù)據(jù) id,有興趣的可以參考一下2019-04-04
java以json格式向后臺(tái)服務(wù)器接口發(fā)送請(qǐng)求的實(shí)例
下面小編就為大家分享一篇java以json格式向后臺(tái)服務(wù)器接口發(fā)送請(qǐng)求的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-01-01
springboot使用Hutool的JschUtil及下載安裝步驟
這篇文章主要為大家介紹了springboot使用Hutool的JschUtil的方法及下載安裝詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
java byte數(shù)組與16進(jìn)制間相互轉(zhuǎn)換的示例
這篇文章主要介紹了java byte數(shù)組與16進(jìn)制間相互轉(zhuǎn)換的示例,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-10-10

