File upload and download are often used in R&D. Here I will summarize the steps of file upload and download.
1: Create a new web project and import two jia packages.If you don't have jar packages, please download them online.
2: Write forms on the web interface
Contains file file file fields
The form must be submitted as a post
You must change the unit that uploads the form to a secondary enctype= "multipart/form-data"
<form action="UploadServlet" enctype="multipart/form-data"
method="post">
Then write code in UpLoad Servlet
// You can determine whether the current request is binary, if not terminatable code
if (!ServletFileUpload.isMultipartContent(request)) {
return;
}
First paste in the code, I will explain below:
// Get the FileItemFactory class
// Factory objects capable of creating file input streams
FileItemFactory factory = new DiskFileItemFactory();
// Get the ServletFileUpload object
ServletFileUpload upload = new ServletFileUpload(factory);
// Set the maximum upload size
upload.setSizeMax(3 * 1024 * 1024);
// Setting Upload Character Set (Seems Unusable)
// upload.setHeaderEncoding("utf-8");
// Get a collection of FileItem types by parseRequest method in upload object
List<FileItem> list = upload.parseRequest(request);
// Traversing through all form elements
for (FileItem fi : list) {
// Iterate to the current form element if it is a normal element and here it is a normal element.
if (fi.isFormField()) {
if (fi.getFieldName().equals("username")){
tx.setUsername(fi.getString("utf-8"));}
if (fi.getFieldName().equals("gender")){
System.out.println(fi.getString("utf-8"));
tx.setGender(fi.getString("utf-8"));}
} else {
// If it is a file field
// Get the name of the file uploaded by the user
// String filename = fi.getName();
if(!"".equals(fi.getName())||null!=fi.getName()){
// Use time offset and random numbers to generate file names, reducing the probability of duplication
String sui = (int) (Math.random() * 10000000) + "";
String shi = System.currentTimeMillis() + "";
//Time + Random Number + Suffix Name of Upload File Name
String filename;
try {
filename = shi
+ sui
+ fi.getName().substring(
fi.getName().lastIndexOf("."));
// System.out.println(filename);
// Get the real path of the project in the server computer
String path = this.getServletContext()
.getRealPath("upload");
fi.write(new File(path + "/" + filename));
//Set the imgname attribute in the tx object to filename
tx.setImgname(filename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Get the value in the form through the ServletFileUpload class in jar, assign the value to the encapsulated entity entity entity entity class, and add it to the data table. Here I pay special attention to the problem of the next file name. Let me explain.
As a server, the name of the image uploaded by the client may be the same, but we can't be the same when we save it to the database. In this case, the uploaded image will be overwritten. We need to name the user's image, which is the code below.
// Use time offset and random numbers to generate file names, reducing the probability of duplication
String sui = (int) (Math.random() * 10000000) + "";
String shi = System.currentTimeMillis() + "";
//Time + Random Number + Suffix Name of Upload File Name
String filename;
try {
filename = shi
+ sui
+ fi.getName().substring(
fi.getName().lastIndexOf("."));
// System.out.println(filename);
Then save the image uploaded by the user
// Get the real path of the project in the server computer
String path = this.getServletContext()
.getRealPath("upload");
fi.write(new File(path + "/" + filename));
//Set the imgname attribute in the tx object to filename
In this way, the picture is saved in the upload folder.
By the way, I missed a point. Let me tell you about the upload file.
It was built under webRoot
In this way, the folder will appear under tomcat, and the images uploaded by users will be saved here.
Here is a picture uploaded from the client to the server.
The above content is all picture upload operation, let me talk about picture download, that is, download the picture from the server to the client, directly upload the code.
<td><a href="DownLoadServlet?imgname=${t.imgname }">download</a></td>
Here is the web download, click Download to jump to DownLoad Servlet
Most of the code here is dead. I will not explain it in detail. Students in doubt are welcome to communicate with me.
//Get the file to download
String fname = request.getParameter("imgname");
System.out.println(fname);
// Get the input file stream
InputStream is = this.getServletContext().getResourceAsStream(
"upload\\" + fname);
// Set the response type to a downloadable file
response.setContentType("application/x-msdownload");
// Set the file name of the download file
String file = URLEncoder.encode("Small Ice Storage Software" + fname, "utf-8");
// Setting Response Header File Configuration
response.addHeader("Content-Disposition", "attachment; filename=\""
+ file + "\"");
// output stream
ServletOutputStream out = response.getOutputStream();
byte[] bs = new byte[is.available()];
// Get the file input stream
is.read(bs);
// Output the file to the client
out.write(bs);
out.close();
is.close();