JAVA USES commos fileupload to realize fileupload and download instance resolution
- 2020-04-01 04:39:36
- OfStack
First, I will introduce the uploading of a file
Entity class
import java.sql.Timestamp;
public class Upfile {
private String id;//The ID primary key is randomly generated using the uuid
private String uuidname; //UUID name
private String filename;//The file name
private String savepath; //Save the path
private Timestamp uploadtime; //Upload time
private String description;//The file
private String username; //The user name
public Upfile() {
super();
}
public Upfile(String id, String uuidname, String filename, String savepath,
Timestamp uploadtime, String description, String username) {
super();
this.id = id;
this.uuidname = uuidname;
this.filename = filename;
this.savepath = savepath;
this.uploadtime = uploadtime;
this.description = description;
this.username = username;
}
public String getDescription() {
return description;
}
public String getFilename() {
return filename;
}
public String getId() {
return id;
}
public String getSavepath() {
return savepath;
}
public Timestamp getUploadtime() {
return uploadtime;
}
public String getUsername() {
return username;
}
public String getUuidname() {
return uuidname;
}
public void setDescription(String description) {
this.description = description;
}
public void setFilename(String filename) {
this.filename = filename;
}
public void setId(String id) {
this.id = id;
}
public void setSavepath(String savepath) {
this.savepath = savepath;
}
public void setUploadtime(Timestamp uploadtime) {
this.uploadtime = uploadtime;
}
public void setUsername(String username) {
this.username = username;
}
public void setUuidname(String uuidname) {
this.uuidname = uuidname;
}
}
page
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'upload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1> File upload </h1>
<form action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data">
<table>
<tr>
<td> Upload username :</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td> Upload a file :</td>
<td><input type="file" name="file"/></td>
</tr>
<tr>
<td> describe :</td>
<td><textarea rows="5" cols="50" name="description"></textarea></td>
</tr>
<tr>
<td><input type="submit" value=" Upload begins "/></td>
</tr>
</table>
</form>
<div>${msg }</div>
<a href="${pageContext.request.contextPath }/index.jsp"> Return to the home page </a>
</body>
</html>
The Servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.itheima.domain.Upfile;
import com.itheima.exception.MyException;
import com.itheima.service.UpfileService;
import com.itheima.service.impl.UpfileServiceImpl;
import com.itheima.untils.WebUntil;
public class UploadFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Determine if the form is multi-part
if(!ServletFileUpload.isMultipartContent(request)){
request.setAttribute("msg", " Wrong form setting , Please check the enctype Property is whether it is set correctly ");
request.getRequestDispatcher("/upload.jsp").forward(request, response);
return ;
}
//Gets and iterates through a file upload object containing all the information uploaded
try {
Upfile upfile=WebUntil.upload(request);
UpfileService upfileService=new UpfileServiceImpl();
boolean flag=upfileService.add(upfile);
if(flag){
request.setAttribute("msg", " Uploaded successfully ");
request.getRequestDispatcher("/upload.jsp").forward(request, response);
return ;
}else{
request.setAttribute("msg", " Upload failed , Please try again ");
request.getRequestDispatcher("/upload.jsp").forward(request, response);
return ;
}
}catch (FileSizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("msg", " Single file size , Exceed the maximum limit ");
request.getRequestDispatcher("/upload.jsp").forward(request, response);
return ;
} catch (SizeLimitExceededException e) {
e.printStackTrace();
request.setAttribute("msg", " Total file size , Exceed the maximum limit ");
request.getRequestDispatcher("/upload.jsp").forward(request, response);
return ;
}
}
}
Utility class
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.itheima.domain.Upfile;
import com.itheima.exception.MyException;
public class WebUntil {
public static Upfile upload(HttpServletRequest request) throws FileSizeLimitExceededException, SizeLimitExceededException {
Upfile upfile=new Upfile();
ArrayList<String> fileList=initList();
try {
//Gets the disk file object factory
DiskFileItemFactory factory=new DiskFileItemFactory();
String tmp=request.getSession().getServletContext().getRealPath("/tmp");
System.out.println(tmp);
//Initial chemical plant
setFactory(factory,tmp);
//Gets the file upload parser
ServletFileUpload upload=new ServletFileUpload(factory);
//initializer
setUpload(upload);
//Gets a collection of file lists
List<FileItem> list = upload.parseRequest(request);
//traverse
for (FileItem items : list) {
//Determines if it is a normal form object
if(items.isFormField()){
//Gets the name of the upload form
String fieldName=items.getFieldName();
//value
String fieldValue=items.getString("UTF-8");
//judge
if("username".equals(fieldName)){
//Set up the
upfile.setUsername(fieldValue);
}else if("description".equals(fieldName)){
//Set properties
upfile.setDescription(fieldValue);
}
}else{
//Is the file ready to upload
//Get file name
String filename=items.getName();
//Handles differences in filenames obtained from different browsers
int index=filename.lastIndexOf("\");
if(index!=-1){
filename=filename.substring(index+1);
}
//Generate a random file name
String uuidname=generateFilename(filename);
//Gets the path to the uploaded file
String savepath=request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
//Gets the input stream in the request object
InputStream in = items.getInputStream();
//Scatter the files in different paths and figure out the path
savepath=generateRandomDir(savepath,uuidname);
//Copy the file
uploadFile(in,savepath,uuidname);
String id=UUID.randomUUID().toString();
upfile.setId(id);
upfile.setSavepath(savepath);
upfile.setUuidname(uuidname);
upfile.setFilename(filename);
//Clear the cache
items.delete();
}
}
}catch ( FileUploadBase.FileSizeLimitExceededException e) {
//Throw an exception
throw e;
} catch (FileUploadBase.SizeLimitExceededException e) {
//Throw an exception
throw e;
}catch (FileUploadException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return upfile;
}
private static ArrayList<String> initList() {
ArrayList<String> list=new ArrayList<String>();
list.add(".jpg");
list.add(".rar");
list.add(".txt");
list.add(".png");
return list;
}
private static void uploadFile(InputStream in, String savepath,
String uuidname) {
//Access to the file
File file=new File(savepath, uuidname);
OutputStream out = null;
try {
int len=0;
byte [] buf=new byte[1024];
//Get the output stream
out = new FileOutputStream(file);
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String generateRandomDir(String savepath, String uuidname) {
//Into a hashcode
System.out.println(" Upload path "+savepath);
System.out.println("UUIDNAME"+uuidname);
int hashcode=uuidname.hashCode();
//The container
StringBuilder sb=new StringBuilder();
while(hashcode>0){
//With 15
int tmp=hashcode&0xf;
sb.append("/");
sb.append(tmp+"");
hashcode=hashcode>>4;
}
//Splicing new paths
String path=savepath+sb.toString();
System.out.println("path"+path);
File file=new File(path);
//Determine whether the path exists or not
if(!file.exists()){
//Create if it doesn't exist
file.mkdirs();
}
//Back to save path
return path;
}
private static String generateFilename( String filename) {
String uuidname=UUID.randomUUID().toString();
return uuidname.replace("-", "").toString()+"_"+filename;
}
private static void setUpload(ServletFileUpload upload) {
// Set up the A character encoding
upload.setHeaderEncoding("utf-8");
//Set file size
upload.setFileSizeMax(1024*1024*20);
//Set the total file size
upload.setSizeMax(1024*1024*50);
//Set the progress listener
upload.setProgressListener(new ProgressListener() {
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println(" Have read : "+pBytesRead+", A total of : "+pContentLength+", The first "+pItems+" a ");
}
});
}
private static void setFactory(DiskFileItemFactory factory, String tmp) {
//Configure the initialization value buffer
factory.setSizeThreshold(1024*1024);
File file=new File(tmp);
//Set the buffer directory
factory.setRepository(file);
}
}
Ii file download
The Servlet
public class DownupfileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get the ID
String id=request.getParameter("id");
//Interfaces at the business layer
UpfileService upfileService=new UpfileServiceImpl();
//Find the object by ID
Upfile upfile=upfileService.findUpfileById(id);
if(upfile==null){
return;
}
//Gets the real name of the file
String filename=upfile.getFilename();
//If there is Chinese in the file name, need to transcode, otherwise there is no file name when downloading
filename=URLEncoder.encode(filename, "utf-8");
//Changed name
String uuidname=upfile.getUuidname();
//Save the path
String savepath=upfile.getSavepath();
File file=new File(savepath,uuidname);
//Determine if the file exists
if(!file.exists()){
request.setAttribute("msg", " download The file is out of date ");
request.getRequestDispatcher("/index").forward(request, response);
return;
}
//Set the file to download the response header information
response.setHeader("Content-disposition", "attachement;filename="+filename);
//Use IO stream output
InputStream in = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
int len=0;
byte [] buf=new byte[1024];
while((len=in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
}
}
The database
create database upload_download_exercise;
use upload_download_exercise;
create table upfiles(
id varchar(100), //Generate using UUID
uuidname varchar(255),//Uuid plus the original file name
filename varchar(100),//Real file name
savepath varchar(255),//Save the path
uploadtime timestamp,//Upload time
description varchar(255),//describe
username varchar(10) The heir
);
Above is the site for you to share the use of JAVA commos-fileupload fileupload and download related content, I hope to help you.