Загрузка файлов
Для того, чтобы загрузить файл, мы можем воспользоваться классом DiskFileItemFactory, который входит в пакет org.apache.commons.fileupload.
Далее нам необходимо указать место на диске, куда мы будем сохранять данный файл, и выполнить несколько настроек.
Для понимания того, как это работает на практике, рассмотрим простой пример.
В качестве основы возьмем приложение из данной статьи.
Класс FileUploadDemo.java
package net.proselyte.servletstutorial;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
/**
* Simple servlet that demonstrates file uploading using org.apache.commons.
*
* @author Eugene Suleimanov
*/
public class FileUploadDemo extends HttpServlet {
static final int fileMaxSize = 100 * 1024;
static final int memMaxSize = 100 * 1024;
private String filePath = "/home/proselyte/Programming/Projects/SerlvetsTutorial/src/main/resources/uploads/";
private File file;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String docType = "
<
!DOCTYPE html
>
";
String title = "File Uploading Demo";
PrintWriter writer = response.getWriter();
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(new File(filePath));
diskFileItemFactory.setSizeThreshold(memMaxSize);
ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
upload.setSizeMax(fileMaxSize);
try {
List fileItems = upload.parseRequest(request);
Iterator iterator = fileItems.iterator();
writer.println(docType +
"
<
html
>
" +
"
<
head
>
" +
"
<
title
>
" + title + "
<
/title
>
" +
"
<
/head
>
" +
"
<
body
>
");
while (iterator.hasNext()) {
FileItem fileItem = (FileItem) iterator.next();
if (!fileItem.isFormField()) {
String fileName = fileItem.getName();
if (fileName.lastIndexOf("\\")
>
= 0) {
file = new File(filePath +
fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(filePath +
fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fileItem.write(file);
writer.println(fileName + " is uploaded.
<
br
>
");
}
}
writer.println("
<
/body
>
" +
"
<
/html
>
");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Файл web.xml
<
!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"
>
<
web-app
>
<
display-name
>
Servlets Tutorial
<
/display-name
>
<
servlet
>
<
servlet-name
>
SimpleServlet
<
/servlet-name
>
<
servlet-class
>
net.proselyte.servletstutorial.SimpleServlet
<
/servlet-class
>
<
/servlet
>
<
servlet
>
<
servlet-name
>
FileUploadDemo
<
/servlet-name
>
<
servlet-class
>
net.proselyte.servletstutorial.FileUploadDemo
<
/servlet-class
>
<
/servlet
>
<
servlet-mapping
>
<
servlet-name
>
SimpleServlet
<
/servlet-name
>
<
url-pattern
>
/SimpleServlet
<
/url-pattern
>
<
/servlet-mapping
>
<
servlet-mapping
>
<
servlet-name
>
FileUploadDemo
<
/servlet-name
>
<
url-pattern
>
/FileUploadDemo
<
/url-pattern
>
<
/servlet-mapping
>
<
/web-app
>
Файл pom.xml
<
project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
>
<
modelVersion
>
4.0.0
<
/modelVersion
>
<
groupId
>
net.proselyte.tutorials
<
/groupId
>
<
artifactId
>
ServletsTutorial
<
/artifactId
>
<
packaging
>
war
<
/packaging
>
<
version
>
1.0-SNAPSHOT
<
/version
>
<
name
>
Servlets Tutorial
<
ame
>
<
url
>
http://maven.apache.org
<
/url
>
<
properties
>
<
javax.servlet.api.version
>
2.5
<
/javax.servlet.api.version
>
<
tomcat.plugin.version
>
2.2
<
/tomcat.plugin.version
>
<
apache.commons.fileupload.version
>
1.2.2
<
/apache.commons.fileupload.version
>
<
/properties
>
<
dependencies
>
<
dependency
>
<
groupId
>
javax.servlet
<
/groupId
>
<
artifactId
>
servlet-api
<
/artifactId
>
<
version
>
${javax.servlet.api.version}
<
/version
>
<
scope
>
provided
<
/scope
>
<
/dependency
>
<
dependency
>
<
groupId
>
commons-fileupload
<
/groupId
>
<
artifactId
>
commons-fileupload
<
/artifactId
>
<
version
>
${apache.commons.fileupload.version}
<
/version
>
<
/dependency
>
<
/dependencies
>
<
build
>
<
finalName
>
ServletsTutorial
<
/finalName
>
<
plugins
>
<
!-- Tomcat plugin --
>
<
plugin
>
<
groupId
>
org.apache.tomcat.maven
<
/groupId
>
<
artifactId
>
tomcat7-maven-plugin
<
/artifactId
>
<
version
>
${tomcat.plugin.version}
<
/version
>
<
configuration
>
<
path
>
/
<
/path
>
<
port
>
8088
<
/port
>
<
/configuration
>
<
/plugin
>
<
plugin
>
<
groupId
>
org.apache.maven.plugins
<
/groupId
>
<
artifactId
>
maven-compiler-plugin
<
/artifactId
>
<
configuration
>
<
source
>
1.7
<
/source
>
<
target
>
1.7
<
/target
>
<
/configuration
>
<
/plugin
>
<
/plugins
>
<
/build
>
<
/project
>
Страница FileUploadDemo.html
<
html
>
<
head
>
<
title
>
FileUploadDemo
<
/title
>
<
/head
>
<
body
>
<
h1
>
File Upload Demo
<
/h1
>
<
h3
>
Please, select file to upload
<
/h3
>
<
br/
>
<
form action="FileUploadDemo" method="post"
enctype="multipart/form-data"
>
<
input type="file" name="file" size="100"/
>
<
br/
>
<
input type="submit" value="Upload File"/
>
<
/form
>
<
/body
>
<
/html
>
После этого необходимо в консоли выполнить команду:
mvn tomcat7:run
И перейти по ссылке:
http://localhost:8088/FileUploadDemo.html
В результате мы получим следующие страницы:
FileUploadDemo.html
После нажатия кнопки Browse
После выбора файла temp1.txt
После нажатия кнопки Upload File:
В результате в указанной нами директории появится выбранный файл: