Build the Environment
Here, use Maven to import the jar package:
<dependencies>
<!--file Upload--
<dependency>
<groupid>commons-fileupload</ groupid>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version >
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency >
<!--json-->
<dependency>
<groupId>org.json</groupId>
< artifactid>json</artifactid>
<version>20160810</version>
</dependency>
</dependencies>
Three main jar packages, which will also use jquery and submit forms asynchronously, so jquery and Jquery.form files are required
JSP page
<%--Created by IntelliJ idea. USER:WQH DATE:2017/5/26 time:9:46 To change this template use File | Settings |
File Templates. --%> <%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>
servlet Code
File upload test, upload files will not be saved to the local L. Returns the file name directly to the page and returns the JSON format.
Req.setcharacterencoding ("Utf-8");
Resp.setcharacterencoding ("Utf-8");
list<string> fileName = new arraylist<> ();
Boolean ismultipartcontent = Servletfileupload.ismultipartcontent (req);
Determine if the file is uploaded if (ismultipartcontent) {Diskfileitemfactory factory = new Diskfileitemfactory ();
Servletfileupload fileUpload = new Servletfileupload (factory);
try {list<fileitem> fileitems = fileupload.parserequest (req);
for (Fileitem fileitem:fileitems) {//To determine the type of field if (Fileitem.isformfield ()) {
Working with normal fields} else{//file fields, processing the upload field, this will not save the file locally.
Filename.add (Fileitem.getname ());
}}} catch (Fileuploadexception e) {e.printstacktrace ();
}//Convert list to JSONint index = 1;
Jsonarray Jsonarray = new Jsonarray ();
for (String s:filename) {jsonobject jsonobject = new Jsonobject ();
Jsonobject.put ("file", s);
Jsonarray.put (Jsonobject);
} resp.getwriter (). print (Jsonarray);
}
Test
Select the uploaded file
File upload test and return JSON format file name successfully: