I have nothing to do, so I wrote a servlet to implement the upload and download function. After starting the service, you can be a small file server in a LAN.
1. Preparation
Download two jar packages:
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
2. Create a web project
My project is called: z-upload
3. Configure web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>z-upload</display-name> <servlet> <servlet-name>UploadService</servlet-name> <servlet-class>com.syz.servlet.UploadService</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadService</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping></web-app>
From the above configuration, we can see that my servlet class is UploadService, and the matching url is /*, which means matching all access urls.
4. Write servlet class
package com.syz.servlet;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Iterator;import java.util.List;import javax.servlet.ServletContext;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;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;public class UploadServlet extends HttpServlet { public static final String LIST = "/list"; public static final String FORM = "/form"; public static final String HANDLE = "/handle"; public static final String DOWNLOAD = "/download"; public static final final String DELETE = "/delete"; public static final String UPLOAD_DIR = "/upload"; private static final long serialVersionUID = 2170797039752860765L; public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("execute..."); System.out.println("------------begin---------------"); req.setCharacterEncoding("UTF-8"); String host = req.getRemoteHost(); System.out.println("host:" + host); String uri = req.getRequestURI(); System.out.println("uri:" + uri); ServletContext servletContext = this.getServletConfig() .getServletContext(); // The base path to upload the file String basePath = servletContext.getRealPath(UPLOAD_DIR); // Context path String contextPath = servletContext.getContextPath(); System.out.println("contextPath:" + contextPath); // Path after intercepting the context String action = uri.substring(contextPath.length()); System.out.println("action:" + action); // Different processing is performed according to different actions if (action.equals(FORM)) { form(contextPath, resp); } else if (action.equals(HANDLE)) { boolean isMultipart = ServletFileUpload.isMultipartContent(req); System.out.println("isMultipart:" + isMultipart); if (!isMultipart) { return; } DiskFileItemFactory factory = new DiskFileItemFactory(); File repository = (File) servletContext .getAttribute(ServletContext.TEMPDIR); System.out.println("repository:" + repository.getAbsolutePath()); System.out.println("basePath:" + basePath); factory.setSizeThreshold(1024 * 100); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); // Create a listener ProgressListener progressListener = new ProgressListener() { public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("Current file size:" + pContentLength + "/t already processed:" + pBytesRead); } }; upload.setProgressListener(progressListener); List<FileItem> items = null; try { items = upload.parseRequest(req); System.out.println("items size:" + items.size()); Iterator<FileItem> item = items.iterator(); while(ite.hasNext()){ FileItem item = item.next(); if(item.isFormField()){ // handle FormField }else{ // handle file String fieldName = item.getFieldName(); String fileName = item.getName(); fileName = fileName.substring( fileName.lastIndexOf(File.separator) + 1); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); System.out.println(fieldName + "/t" + fileName + "/t" + contentType + "/t" + isInMemory + "/t" + sizeInBytes); File file = new File( basePath + "/" + fileName + "_" + getSuffix()); // item.write(file); InputStream in = item.getInputStream(); OutputStream out = new FileOutputStream(file); byte[] b = new byte[1024]; int n = 0; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } out.flush(); in.close(); out.close(); } } // Redirect to the file list page after processing String href1 = contextPath + LIST; resp.sendRedirect(href1); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } else if (action.equals(LIST)) { list(contextPath, basePath, resp); } else if (action.equals(DOWNLOAD)) { String id = req.getParameter("id"); System.out.println("id:" + id); if (id == null) { return; } File file = new File(basePath); File[] list = file.listFiles(); int len = list.length; boolean flag = false; for (int i = 0; i < len; i++) { File f = list[i]; String fn = f.getName(); if (f.isFile() && fn.lastIndexOf("_") > -1) { String fid = fn.substring(fn.lastIndexOf("_")); if (id.equals(fid)) { download(f, resp); flag = true; break; } } } if (!flag) { notfound(contextPath, resp); } } else if (action.equals(DELETE)) { String id = req.getParameter("id"); System.out.println("id:" + id); if (id == null) { return; } File file = new File(basePath); File[] list = file.listFiles(); int len = list.length; boolean flag = false; for (int i = 0; i < len; i++) { File f = list[i]; String fn = f.getName(); if (f.isFile() && fn.lastIndexOf("_") > -1) { String fid = fn.substring(fn.lastIndexOf("_")); if (id.equals(fid)) { f.delete(); flag = true; break; } } } if (flag) { // Redirect to the file list page after processing String href1 = contextPath + LIST; resp.sendRedirect(href1); } else { notfound(contextPath, resp); } } else { show404(contextPath, resp); } System.out.println("--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- PrintWriter out = resp.getWriter(); String href1 = contextPath + LIST; out.write("<html>"); out.write("<head><title>404</title></head>"); out.write("<body>"); out.write("<b>The page you are visiting does not exist! <a href='" + href1 + "'>Click</a> to return to file list</b>"); out.write("</body>"); out.write("</html>"); out.close(); } private void form(String contextPath, HttpServletResponse resp) throws IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); String href1 = contextPath + LIST; out.write("<html>"); out.write("<head><title>form</title></head>"); out.write("<body>"); out.write("<b><a href='" + href1 + "'>Click</a> to return to file list</b>"); out.write( "<form action='handle' method='post' enctype='multipart/form-data' style='margin-top:20px;'>"); out.write("<input name='file' type='file'/><br>"); out.write("<input type='submit' value='Upload'/><br>"); out.write("</form>"); out.write("</body>"); out.write("</html>"); out.close(); } private void notfound(String contextPath, HttpServletResponse resp) throws IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); String href1 = contextPath + LIST; out.write("<html><body><b>Operation failed! The file does not exist or the file has been deleted! <a href='" + href1 + "'>Click</a> to return to the file list</b></body></html>"); out.close(); } private void download(File f, HttpServletResponse resp) throws IOException { String fn = f.getName(); String fileName = fn.substring(0, fn.lastIndexOf("_")); System.out.println("fileName:" + fileName); resp.reset(); resp.setContentType("application/octet-stream"); String encodingFilename = new String(fileName.getBytes("GBK"), "ISO8859-1"); System.out.println("encodingFilename:" + encodingFilename); resp.setHeader("content-disposition", "attachment;filename=" + encodingFilename); InputStream in = new FileInputStream(f); OutputStream out = resp.getOutputStream(); byte[] b = new byte[1024]; int n = 0; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } out.flush(); in.close(); out.close(); } private void list(String contextPath, String basePath, HttpServletResponse resp) throws IOException { String href_u = contextPath + FORM; resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); out.write("<html>"); out.write("<head><title>list</title></head>"); out.write("<body>"); out.write("<b>I want <a href='" + href_u + "'>Upload</a></b><br>"); out.write( "<table border='1' style='border-collapse:collapse;width:100%;margin-top:20px;'>"); out.write("<thead>"); out.write("<tr>"); out.write("<th>serial number</th><th>file name</th><th>operation</th>"); out.write("</tr>"); out.write("</tr>"); out.write("<tbody>"); File file = new File(basePath); File[] list = file.listFiles(); System.out .println("basePath:" + basePath + "/tlist.size:" + list.length); int len = list.length; int no = 1; for (int i = 0; i < len; i++) { File f = list[i]; System.out.println(i + "/t" + f.getName()); String fn = f.getName(); if (f.isFile() && fn.lastIndexOf("_") > -1) { String filename = fn.substring(0, fn.lastIndexOf("_")); String id = fn.substring(fn.lastIndexOf("_")); String href1 = contextPath + DOWNLOAD + "?id=" + id; String href2 = contextPath + DELETE + "?id=" + id; StringBuilder sb = new StringBuilder(); sb.append("<tr>"); sb.append("<td>"); sb.append(no++); sb.append("</td>"); sb.append("<td>"); sb.append(filename); sb.append("</td>"); sb.append("<td>"); sb.append("<a href='"); sb.append(href1); sb.append("'>Download</a> <a href='"); sb.append(href2); sb.append("' onclick='return confirm(/"Are you sure you want to delete it? /");'>Delete</a>"); sb.append("</td>"); sb.append("</tr>"); out.write(sb.toString()); } } out.write("</tbody>"); out.write("</table>"); out.write("</body>"); out.write("</html>"); out.close(); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doGet..."); execute(req, resp); } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doPost..."); execute(req, resp); } private String getSuffix() { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String suffix = sdf.format(date); return suffix; }}In fact, the UploadService class can directly implement the service method without implementing the doGet and doPost methods.
I don't want to explain anything about the above servlets, just read the code for yourself.
5. Reproduction diagram
1. Project structure diagram
Page 2.404
/* will match all null characters, so the path in the picture will match, which appears in else in the if judgment in UploadService, because the action at this time is a null character.
3. File list page
4. Upload form page
5. Download
6. Delete
7. The file cannot be found. If the file no longer exists on the server when you click Delete, then you will enter this page.
8. Packaged source code projects and war packages
Among them, z-upload is the eclipse source code project, and z-upload.war is the ready war package
There are only two jar packages in the whole project, one web.xml and one servlet class. You can copy it from the article and test it. If you are lazy, you can download it.
http://download.csdn.net/detail/yunsyz/9569680, special reminder, download it for 1 point.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.