java組件commons-fileupload實現(xiàn)文件上傳
一、所需要的包:
1、commons-fileupload-1.2.1.jar:
下載地址
http://commons.apache.org/downloads/download_fileupload.cgi
2、commons-io-1.4.jar:
下載地址
http://commons.apache.org/downloads/download_io.cgi
二、注意事項:
form表單里面要加上enctype="multipart/form-data"
三、代碼示例
1、jsp代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>upload</title> </head> <body> <form action="uploadServlet" method="post" enctype="multipart/form-data"> <table> <caption>上傳實例</caption> <tr> <td>姓名</td> <td> <input type="text" name="name"> </td> </tr> <tr> <td>年齡</td> <td> <input type="text" name="age"> </td> </tr> <tr> <td>照片</td> <td> <input type="file" name="image"> </td> </tr> <tr> <td></td> <td> <input type="submit" value="提交"> </td> </tr> </table> </form> </body> </html>
2、UploadServlet代碼
package servlet;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
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.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
/**
* 上傳servlet
* @author lisanlai
*
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
// 設置字符編碼為UTF-8, 這樣支持漢字顯示
response.setCharacterEncoding("UTF-8");
Writer o = response.getWriter();
/**
* 首先判斷form的enctype是不是multipart/form-data
* 同時也判斷了form的提交方式是不是post
* 方法:isMultipartContent(request)
*/
if(ServletFileUpload.isMultipartContent(request)){
request.setCharacterEncoding("utf-8");
// 實例化一個硬盤文件工廠,用來配置上傳組件ServletFileUpload
DiskFileItemFactory factory = new DiskFileItemFactory();
//設置文件存放的臨時文件夾,這個文件夾要真實存在
File fileDir = new File("../webapps/fileupload/tmp/");
if(fileDir.isDirectory() && fileDir.exists()==false){
fileDir.mkdir();
}
factory.setRepository(fileDir);
//設置最大占用的內(nèi)存
factory.setSizeThreshold(1024000);
//創(chuàng)建ServletFileUpload對象
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setHeaderEncoding("utf-8");
//設置單個文件最大值byte
sfu.setFileSizeMax(102400000);
//所有上傳文件的總和最大值byte
sfu.setSizeMax(204800000);
List<FileItem> items = null;
try {
items = sfu.parseRequest(request);
}catch (SizeLimitExceededException e) {
System.out.println("文件大小超過了最大值");
} catch(FileUploadException e) {
e.printStackTrace();
}
//取得items的迭代器
Iterator<FileItem> iter = items==null?null:items.iterator();
//圖片上傳后存放的路徑目錄
File images = new File("D:/upload/images/");
if(images.exists()==false){
images.mkdirs();
}
//迭代items
while(iter!=null && iter.hasNext()){
FileItem item = (FileItem) iter.next();
//如果傳過來的是普通的表單域
if(item.isFormField()){
System.out.print("普通的表單域:");
System.out.print(new String(item.getFieldName()) + " ");
System.out.println(new String(item.getString("UTF-8")));
}
//文件域
else if(!item.isFormField()){
System.out.println("源圖片:" + item.getName());
String fileName = item.getName().substring(item.getName().lastIndexOf("\\"));
BufferedInputStream in = new BufferedInputStream(item.getInputStream());
//文件存儲在D:/upload/images目錄下,這個目錄也得存在
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(images.getAbsolutePath()+ fileName)));
Streams.copy(in, out, true);
o.write("文件上傳成功");
}
}
}else {
System.out.println("表單的enctype 類型錯誤");
}
}
}
3、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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>UploadTest</display-name> <welcome-file-list> <welcome-file>upload.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>servlet.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/uploadServlet</url-pattern> </servlet-mapping> </web-app>
本文已被整理到了《Java上傳操作技巧匯總》,歡迎大家學習閱讀。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- java組件SmartUpload和FileUpload實現(xiàn)文件上傳功能
- Java中使用fileupload組件實現(xiàn)文件上傳功能的實例代碼
- java使用common-fileupload實現(xiàn)文件上傳
- java組件commons-fileupload實現(xiàn)文件上傳、下載、在線打開
- Java組件commons fileupload實現(xiàn)文件上傳功能
- JavaEE組件commons-fileupload實現(xiàn)文件上傳、下載
- java組件commons-fileupload文件上傳示例
- java組件fileupload文件上傳demo
- JAVA使用commos-fileupload實現(xiàn)文件上傳與下載實例解析
- 使用fileupload組件實現(xiàn)文件上傳功能
相關文章
Spring Boot JPA中使用@Entity和@Table的實現(xiàn)
這篇文章主要介紹了Spring Boot JPA中使用@Entity和@Table的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03
java實現(xiàn)阿拉伯數(shù)字轉(zhuǎn)漢字數(shù)字
這篇文章主要為大家詳細介紹了java實現(xiàn)阿拉伯數(shù)字轉(zhuǎn)換為漢字數(shù)字源代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-04-04
java如何判斷一個數(shù)是否是素數(shù)(質(zhì)數(shù))
這篇文章主要介紹了java如何判斷一個數(shù)是否是素數(shù)(質(zhì)數(shù)),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
IntelliJ IDEA 2018 最新激活碼(截止到2018年1月30日)
這篇文章主要介紹了IntelliJ IDEA 2018 最新激活碼(截止到2018年1月30日)的相關資料,需要的朋友可以參考下2018-01-01

