First, let me introduce the upload of a file
Entity Class
import java.sql.Timestamp; /** * * @Described file upload entity class* */ public class Upfile { private String id;// ID primary key randomly generates private String uuidname; // UUID name private String filename;// File name private String savepath; // Save path private Timestamp uploadtime; // Upload time private String description;// File description private String username; // Username 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 file:</td> <td><input type="file" name="file"/></td> </tr> <tr> <td> Description:</td> <td><textarea rows="5" cols="50" name="description"></textarea></td> </tr> <tr> <td><input type="submit" value="upload start"/></td> </tr> </table> </form> <div>${msg }</div> <a href="${pageContext.request.contextPath }/index.jsp">Return to home page</a> </body> </html> 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 { //Judge whether the form is composed of multiple parts if(!ServletFileUpload.isMultipartContent(request)){ request.setAttribute("msg", "Individual settings of the form, please check whether the enctype attribute is set correctly"); request.getRequestDispatcher("/upload.jsp").forward(request, response); return ; } //If it is a multi-part, get and traverse to return a file upload object, containing all the uploaded information try { Upfile upfile=WebUntil.upload(request); UpfileService upfileService=new UpfileServiceImpl(); boolean flag=upfileService.add(upfile); if(flag){ request.setAttribute("msg", "Upload successful"); 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, exceeding the maximum limit"); request.getRequestDispatcher("/upload.jsp").forward(request, response); return ; } catch (SizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("msg", "Total file size, exceeding the maximum limit"); request.getRequestDispatcher("/upload.jsp").forward(request, response); return ; } } }Tools
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.UsupportedEncodingException; 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.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; /** * File upload tool class* @Describe TODO * */ public class WebUntil { /** * File upload method* @param request Pass the request parameter in * @return Return an Upfile object* @throws FileSizeLimitExceededException * @throws SizeLimitExceededException * @throws IOException */ public static Upfile upload(HttpServletRequest request) throws FileSizeLimitExceededException, SizeLimitExceededException { Upfile upfile=new Upfile(); ArrayList<String> fileList=initList(); try { //Get disk file object factory DiskFileItemFactory factory=new DiskFileItemFactory(); String tmp=request.getSession().getServletContext().getRealPath("/tmp"); System.out.println(tmp); //Initialize factory setFactory(factory,tmp); //Get file upload parser ServletFileUpload upload=new ServletFileUpload(factory); //Initialize parser setUpload(upload); //Get file list<FileItem> list = upload.parseRequest(request); //Travel for (FileItem items: list) { //Judge whether it is an ordinary form object if(items.isFormField()){ //Get the name of the upload form String fieldName=items.getFieldName(); //Value String fieldValue=items.getString("UTF-8"); //Judge if("username".equals(fieldName)){ //Set upfile.setUsername(fieldValue); }else if("description".equals(fieldName)){ //Set the attribute upfile.setDescription(fieldValue); } }else{ //Are the file ready to upload//Get the file name String filename=items.getName(); //handle the differences in file names obtained due to different browsers int index=filename.lastIndexOf("//"); if(index!=-1){ filename=filename.substring(index+1); } //Generate random file names String uuidname=generateFilename(filename); //Get uploaded file path String savepath=request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); //Get input stream in the request object InputStream in = items.getInputStream(); //Break the file and store it in different paths, find 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 cache items.delete(); } } } catch ( FileUploadBase.FileSizeLimitExceededException e) { //Top an exception throw e; } catch (FileUploadBase.SizeLimitExceededException e) { //Exception throws e; }catch (FileUploadException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return upfile; } /** * Initialize file list* @return */ 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; } /** * Copy file* Input stream in @param in items* @param savepath Save path* @param uuidname File name*/ private static void uploadFile(InputStream in, String savepath, String uuidname) { //Get 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(); } } } /** * Generate random storage path* @param savepath Save path* @param uuidname The generated uuid name* @return * Use hashcode to complete*/ private static String generateRandomDir(String savepath, String uuidname) { //Convert to hashcode System.out.println("upload path"+savepath); System.out.println("UUIDNAME"+uuidname); int hashcode=uuidname.hashCode(); //Container StringBuilder sb=new StringBuilder(); while(hashcode>0){ //Int 15 int tmp=hashcode&0xf; sb.append("/"); sb.append(tmp+""); hashcode=hashcode>>4; } //Split new path String path=savepath+sb.toString(); System.out.println("path"+path); File file=new File(path); //Judge whether the path exists if(!file.exists()){ //Create file.mkdirs(); } //Return the save path return path; } /** * Generate a new file name* @param uuidname Random ID name* @param filename Original name* @return */ private static String generateFilename( String filename) { String uuidname=UUID.randomUUID().toString(); return uuidname.replace("-", "").toString()+"_"+filename; } /** * Initialization parser* @param upload */ private static void setUpload(ServletFileUpload upload) { // Set character encoding upload.setHeaderEncoding("utf-8"); // Set file size upload.setFileSizeMax(1024*1024*20); // Set total file size upload.setSizeMax(1024*1024*50); // Set progress listener upload.setProgressListener(new ProgressListener() { public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("Read: "+pBytesRead+", total: "+pContentLength+", "+pItems+"); } }); } /** * Factory initialization method* @param factory * @param tmp Buffer directory*/ 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); } } Download two files
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 ID String id=request.getParameter("id"); //The interface of the business layer UpfileService upfileService=new UpfileServiceImpl(); //Find this object based on the ID Upfile upfile=upfileService.findUpfileById(id); if(upfile==null){ return; } //Get the real name of the file String filename=upfile.getFilename(); //If there is Chinese in the file name, it needs to be transcoded, otherwise there will be no file name filename=URLEncoder.encode(filename, "utf-8"); //Changed name String uuidname=upfile.getUuidname(); //Save path String savepath=upfile.getSavepath(); File file=new File(savepath,uuidname); //Determine if the file exists if(!file.exists()){ request.setAttribute("msg", "The downloaded file has expired"); request.getRequestDispatcher("/index").forward(request, response); return; } //Set the file download response header information response.setHeader("Content-disposition", "attachement;filename="+filename); //Use IO stream to 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(); } }database
create database upload_download_exercise; use upload_download_exercise; create table upfiles( id varchar(100), //Use UUID to generate uuidname varchar(255), //Uuid plus the original file name filename varchar(100), //Real file name savepath varchar(255), //Save path uploadtime timestamp,//Upload time description varchar(255),//Describe username varchar(10) uploader);
The above is the relevant content of JAVA using commos-fileupload to achieve file upload and download, I hope it will be helpful to everyone.