Upload & Download

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Upload Demo:

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        boolean isMulti = ServletFileUpload.isMultipartContent(req);
        if (isMulti) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            try {
                Iterator items = upload.parseRequest(new ServletRequestContext(req)).iterator();
                while (items.hasNext()) {
                    FileItem item = (FileItem) items.next();
                    if (!item.isFormField()) {
                        String name = item.getName();
                        String fileName = name.substring(name.lastIndexOf('\\') + 1);
                        String path = req.getRealPath("file") + File.separatorChar + fileName;
                        File uploadedFile = new File(path);
                        String foo = path.substring(0, path.lastIndexOf('\\'));
                        File bar = new File(foo);
                        if (!bar.exists())
                            bar.mkdirs();
                        item.write(uploadedFile);
//                        PrintWriter out = resp.getWriter();
                        out.print(" 上传的文件为: " + name + "<br>");
                        out.print("保存的地址: " + path );
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Download Demo:

Content-disposition is an extension to the MIME protocol. MIME protocol indicates MIME user agent how to display the attached file. Content-disposition can actually control the content of the resulting user requests a file when saved as a default file name, the file is displayed directly in the browser or pop-up file when you access the download dialog box.
The key is

resp.setContentType("application/force-download");

Then flow through the operation to complete the file operation.

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String fileName = "test.txt";
            resp.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            resp.setContentType("application/force-download");
            OutputStream out; //输出流
            InputStream in; //输入流
            out = resp.getOutputStream();
            int byteSent;
            byte[] buff = new byte[512];
            in = new FileInputStream(new File(req.getRealPath(fileName)));
            while ((byteSent = in.read(buff)) != -1)
                out.write(buff, 0, byteSent);
            in.close();
            out.close();
        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <welcome-file-list>
        <welcome-file>UploadFileDemo.jsp</welcome-file>
    </welcome-file-list>
    <filter>
        <filter-name>SetChar</filter-name>
        <filter-class>SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
        <init-param>
            <param-name>enable</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>SetChar</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>ArbitraryName_Whatever</servlet-name>
        <servlet-class>MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ArbitraryName_Whatever</servlet-name>
        <url-pattern>/FormActionName</url-pattern>
    </servlet-mapping>
</web-app>

Notes on the file path

Here Insert Picture Description
This results obtained are four lines of code:
Here Insert Picture Description
directory structure:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_44090305/article/details/93772466