Skip to content

Commit 568f012

Browse files
committed
servlet file upload
servlet file upload
1 parent a4a2aa3 commit 568f012

24 files changed

+8808
-0
lines changed

servlet-file-upload/.classpath

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<classpath>
3+
<classpathentry kind="src" path="src/test/java" output="target/test-classes" including="**/*.java"/>
4+
<classpathentry kind="src" path="src/main/java" including="**/*.java"/>
5+
<classpathentry kind="output" path="target/classes"/>
6+
<classpathentry kind="var" path="M2_REPO/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar"/>
7+
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
8+
<classpathentry kind="var" path="M2_REPO/commons-fileupload/commons-fileupload/1.3/commons-fileupload-1.3.jar"/>
9+
<classpathentry kind="var" path="M2_REPO/commons-io/commons-io/2.4/commons-io-2.4.jar"/>
10+
<classpathentry kind="var" path="M2_REPO/com/fasterxml/jackson/core/jackson-core/2.2.2/jackson-core-2.2.2.jar"/>
11+
<classpathentry kind="var" path="M2_REPO/com/fasterxml/jackson/core/jackson-databind/2.2.2/jackson-databind-2.2.2.jar"/>
12+
<classpathentry kind="var" path="M2_REPO/com/fasterxml/jackson/core/jackson-annotations/2.2.2/jackson-annotations-2.2.2.jar"/>
13+
</classpath>

servlet-file-upload/pom.xml

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
5+
<groupId>com.hmkcode</groupId>
6+
<artifactId>servlet-file-upload</artifactId>
7+
<version>1.0-SNAPSHOT</version>
8+
<packaging>jar</packaging>
9+
10+
<name>servlet-file-upload</name>
11+
<url>http://maven.apache.org</url>
12+
13+
<properties>
14+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15+
</properties>
16+
17+
<dependencies>
18+
<dependency>
19+
<groupId>javax.servlet</groupId>
20+
<artifactId>javax.servlet-api</artifactId>
21+
<version>3.1.0</version>
22+
</dependency>
23+
<dependency>
24+
<groupId>commons-fileupload</groupId>
25+
<artifactId>commons-fileupload</artifactId>
26+
<version>1.3</version>
27+
</dependency>
28+
<dependency>
29+
<groupId>commons-io</groupId>
30+
<artifactId>commons-io</artifactId>
31+
<version>2.4</version>
32+
</dependency>
33+
<dependency>
34+
<groupId>com.fasterxml.jackson.core</groupId>
35+
<artifactId>jackson-core</artifactId>
36+
<version>2.2.2</version>
37+
</dependency>
38+
<dependency>
39+
<groupId>com.fasterxml.jackson.core</groupId>
40+
<artifactId>jackson-databind</artifactId>
41+
<version>2.2.2</version>
42+
</dependency>
43+
<dependency>
44+
<groupId>com.fasterxml.jackson.core</groupId>
45+
<artifactId>jackson-annotations</artifactId>
46+
<version>2.2.2</version>
47+
</dependency>
48+
</dependencies>
49+
50+
<build>
51+
<finalName>servlet-file-upload</finalName>
52+
<plugins>
53+
<plugin>
54+
<groupId>org.eclipse.jetty</groupId>
55+
<artifactId>jetty-maven-plugin</artifactId>
56+
<version>9.0.4.v20130625</version>
57+
</plugin>
58+
</plugins>
59+
</build>
60+
</project>
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package com.hmkcode;
2+
3+
import java.io.IOException;
4+
import java.io.InputStream;
5+
import java.io.OutputStream;
6+
import java.util.LinkedList;
7+
import java.util.List;
8+
import javax.servlet.ServletException;
9+
import javax.servlet.annotation.MultipartConfig;
10+
import javax.servlet.http.HttpServlet;
11+
import javax.servlet.http.HttpServletRequest;
12+
import javax.servlet.http.HttpServletResponse;
13+
import com.fasterxml.jackson.databind.ObjectMapper;
14+
import com.hmkcode.vo.FileMeta;
15+
16+
//this to be used with Java Servlet 3.0 API
17+
@MultipartConfig
18+
public class FileUploadServlet extends HttpServlet {
19+
20+
private static final long serialVersionUID = 1L;
21+
22+
// this will store uploaded files
23+
private static List<FileMeta> files = new LinkedList<FileMeta>();
24+
/***************************************************
25+
* URL: /upload
26+
* doPost(): upload the files and other parameters
27+
****************************************************/
28+
protected void doPost(HttpServletRequest request, HttpServletResponse response)
29+
throws ServletException, IOException{
30+
31+
// 1. Upload File Using Java Servlet API
32+
//files.addAll(MultipartRequestHandler.uploadByJavaServletAPI(request));
33+
34+
// 1. Upload File Using Apache FileUpload
35+
files.addAll(MultipartRequestHandler.uploadByApacheFileUpload(request));
36+
37+
// Remove some files
38+
while(files.size() > 20)
39+
{
40+
files.remove(0);
41+
}
42+
43+
// 2. Set response type to json
44+
response.setContentType("application/json");
45+
46+
// 3. Convert List<FileMeta> into JSON format
47+
ObjectMapper mapper = new ObjectMapper();
48+
49+
// 4. Send resutl to client
50+
mapper.writeValue(response.getOutputStream(), files);
51+
52+
}
53+
/***************************************************
54+
* URL: /upload?f=value
55+
* doGet(): get file of index "f" from List<FileMeta> as an attachment
56+
****************************************************/
57+
protected void doGet(HttpServletRequest request, HttpServletResponse response)
58+
throws ServletException, IOException{
59+
60+
// 1. Get f from URL upload?f="?"
61+
String value = request.getParameter("f");
62+
63+
// 2. Get the file of index "f" from the list "files"
64+
FileMeta getFile = files.get(Integer.parseInt(value));
65+
66+
try {
67+
// 3. Set the response content type = file content type
68+
response.setContentType(getFile.getFileType());
69+
70+
// 4. Set header Content-disposition
71+
response.setHeader("Content-disposition", "attachment; filename=\""+getFile.getFileName()+"\"");
72+
73+
// 5. Copy file inputstream to response outputstream
74+
InputStream input = getFile.getContent();
75+
OutputStream output = response.getOutputStream();
76+
byte[] buffer = new byte[1024*10];
77+
78+
for (int length = 0; (length = input.read(buffer)) > 0;) {
79+
output.write(buffer, 0, length);
80+
}
81+
82+
output.close();
83+
input.close();
84+
}catch (IOException e) {
85+
e.printStackTrace();
86+
}
87+
88+
}
89+
}
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
package com.hmkcode;
2+
3+
import java.io.IOException;
4+
import java.util.Collection;
5+
import java.util.LinkedList;
6+
import java.util.List;
7+
import javax.servlet.ServletException;
8+
import javax.servlet.http.HttpServletRequest;
9+
import javax.servlet.http.Part;
10+
import org.apache.commons.fileupload.FileItem;
11+
import org.apache.commons.fileupload.FileUploadException;
12+
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
13+
import org.apache.commons.fileupload.servlet.ServletFileUpload;
14+
15+
import com.hmkcode.vo.FileMeta;
16+
17+
public class MultipartRequestHandler {
18+
19+
20+
21+
public static List<FileMeta> uploadByJavaServletAPI(HttpServletRequest request) throws IOException, ServletException{
22+
23+
List<FileMeta> files = new LinkedList<FileMeta>();
24+
25+
// 1. Get all parts
26+
Collection<Part> parts = request.getParts();
27+
28+
// 2. Get paramter "twitter"
29+
String twitter = request.getParameter("twitter");
30+
31+
// 3. Go over each part
32+
FileMeta temp = null;
33+
for(Part part:parts){
34+
35+
// 3.1 if part is multiparts "file"
36+
if(part.getContentType() != null){
37+
38+
// 3.2 Create a new FileMeta object
39+
temp = new FileMeta();
40+
temp.setFileName(getFilename(part));
41+
temp.setFileSize(part.getSize()/1024 +" Kb");
42+
temp.setFileType(part.getContentType());
43+
temp.setContent(part.getInputStream());
44+
temp.setTwitter(twitter);
45+
46+
// 3.3 Add created FileMeta object to List<FileMeta> files
47+
files.add(temp);
48+
49+
}
50+
}
51+
return files;
52+
}
53+
54+
public static List<FileMeta> uploadByApacheFileUpload(HttpServletRequest request) throws IOException, ServletException{
55+
56+
List<FileMeta> files = new LinkedList<FileMeta>();
57+
58+
// 1. Check request has multipart content
59+
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
60+
FileMeta temp = null;
61+
62+
// 2. If yes (it has multipart "files")
63+
if(isMultipart){
64+
65+
// 2.1 instantiate Apache FileUpload classes
66+
DiskFileItemFactory factory = new DiskFileItemFactory();
67+
ServletFileUpload upload = new ServletFileUpload(factory);
68+
69+
70+
// 2.2 Parse the request
71+
try {
72+
73+
// 2.3 Get all uploaded FileItem
74+
List<FileItem> items = upload.parseRequest(request);
75+
String twitter = "";
76+
77+
// 2.4 Go over each FileItem
78+
for(FileItem item:items){
79+
80+
// 2.5 if FileItem is not of type "file"
81+
if (item.isFormField()) {
82+
83+
// 2.6 Search for "twitter" parameter
84+
if(item.getFieldName().equals("twitter"))
85+
twitter = item.getString();
86+
87+
} else {
88+
89+
// 2.7 Create FileMeta object
90+
temp = new FileMeta();
91+
temp.setFileName(item.getName());
92+
temp.setContent(item.getInputStream());
93+
temp.setFileType(item.getContentType());
94+
temp.setFileSize(item.getSize()/1024+ "Kb");
95+
96+
// 2.7 Add created FileMeta object to List<FileMeta> files
97+
files.add(temp);
98+
99+
}
100+
}
101+
102+
// 2.8 Set "twitter" parameter
103+
for(FileMeta fm:files){
104+
fm.setTwitter(twitter);
105+
}
106+
107+
} catch (FileUploadException e) {
108+
e.printStackTrace();
109+
}
110+
}
111+
return files;
112+
}
113+
114+
115+
// this method is used to get file name out of request headers
116+
//
117+
private static String getFilename(Part part) {
118+
for (String cd : part.getHeader("content-disposition").split(";")) {
119+
if (cd.trim().startsWith("filename")) {
120+
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
121+
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
122+
}
123+
}
124+
return null;
125+
}
126+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package com.hmkcode.vo;
2+
3+
import java.io.InputStream;
4+
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
5+
6+
7+
@JsonIgnoreProperties({"content"})
8+
public class FileMeta {
9+
10+
11+
12+
private String fileName;
13+
private String fileSize;
14+
private String fileType;
15+
private String twitter;
16+
17+
18+
private InputStream content;
19+
20+
21+
22+
public String getFileName() {
23+
return fileName;
24+
}
25+
public void setFileName(String fileName) {
26+
this.fileName = fileName;
27+
}
28+
public String getFileSize() {
29+
return fileSize;
30+
}
31+
public void setFileSize(String fileSize) {
32+
this.fileSize = fileSize;
33+
}
34+
public String getFileType() {
35+
return fileType;
36+
}
37+
public void setFileType(String fileType) {
38+
this.fileType = fileType;
39+
}
40+
public InputStream getContent(){
41+
return this.content;
42+
}
43+
public void setContent(InputStream content){
44+
this.content = content;
45+
}
46+
public String getTwitter(){
47+
return this.twitter;
48+
}
49+
public void setTwitter(String twitter){
50+
this.twitter = twitter;
51+
}
52+
53+
@Override
54+
public String toString() {
55+
return "FileMeta [fileName=" + fileName + ", fileSize=" + fileSize
56+
+ ", fileType=" + fileType + "]";
57+
}
58+
59+
60+
61+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xmlns="http://java.sun.com/xml/ns/javaee"
4+
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
5+
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
6+
id="WebApp_ID" version="3.0">
7+
<display-name>Archetype Created Web Application</display-name>
8+
<welcome-file-list>
9+
<welcome-file>index.html</welcome-file>
10+
</welcome-file-list>
11+
12+
<servlet>
13+
<servlet-name>upload</servlet-name>
14+
<servlet-class>com.hmkcode.FileUploadServlet</servlet-class>
15+
</servlet>
16+
<servlet-mapping>
17+
<servlet-name>upload</servlet-name>
18+
<url-pattern>/upload</url-pattern>
19+
</servlet-mapping>
20+
</web-app>

0 commit comments

Comments
 (0)