Basic usage of Java web file upload and download

File upload and download

The syntax of MySql is enough to read this article. Delivery address: MySql must know
the use of JSP. It is enough to read this article. Delivery address: JSP must know and know

1. Introduction of file upload

1. There must be a form tag, method = post request method, reason: the length of the file will generally exceed the limit of the get request
2. The encType attribute value of the form tag must be multipart/form-data
3. Use the input tag in the form tag , Type = file to add the uploaded file
4. Use the input tag in the form tag, type = submit to submit to the server
5. Write a Servlet program to receive and process the uploaded file
Note: encType = multipart/form-data means that the submitted data is in multiple pieces (Each form item represents a data segment) is spliced, and then sent to the server in the form of a binary stream

Code demonstration (1): Create Upload.jsp in the web directory

<body>
    <form action="http://localhost:8080/MyTest/upLoadServlet" 
          method="post" enctype="multipart/form-data">
        用户名:<input type="text" name="username"/> <br/>
        头像:<input type="file" name="photo"> <br>
        <input type="submit" value="上传">
    </form>
</body>

Code demonstration (2): Create Servlet program upLoadServlet.java

public class upLoadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request,
           HttpServletResponse response) throws ServletException, IOException {
        System.out.println("上传成功了!");
    }
}

Code demonstration (3): write servlet tags in web.xml

<servlet>
    <servlet-name>upLoadServlet</servlet-name>
    <servlet-class>com.qizegao.servlet.upLoadServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>upLoadServlet</servlet-name>
    <url-pattern>/upLoadServlet</url-pattern>
</servlet-mapping>

Operation result: After
Insert picture description here
clicking upload, the console output: upload is successful!
Insert picture description here
Note: The data of the uploaded file in Google Chrome shows blank lines, but the server can receive the data

2. The server parses the uploaded data

  1. First import two jar packages (fileupload package depends on io package):
    Insert picture description here
  2. Commonly used classes in the two jar packages (the imported jar package is commons):
    (1) ServletFileUpload class, used to parse the uploaded data
    ①public static final boolean isMultipartContent(HttpServletRequest request)
    If the uploaded data is in the form of multiple parts, return true , Only multi-segment data is the file upload
    ②public ServletFileUpload()
    empty parameter constructor
    ③public ServletFileUpload(FileItemFactory fileItemFactory)
    parameter is the constructor of the factory implementation class
    ④public List parseRequest(HttpServletRequest request)
    parses the uploaded data and returns each form item List collection
    (2) FileItem class, representing each form item
    ①public boolean isFormField()
    If the current form item is a normal form item, it returns true, and the file type returns false
    ②public String getFieldName()
    gets the name attribute value of the current form item
    ③public String getString()
    Get the value attribute value of the current form item, the parameter is "UTF-8" to solve the garbled problem
    ④public String getName()
    Get the uploaded file name
    ⑤public void write (File file) write
    the uploaded file to the hard disk location pointed to by the parameter File

Code demonstration (1): Create Upload.jsp in the web directory

<form action="http://localhost:8080/MyTest/upLoadServlet" method="post" enctype="multipart/form-data">
    用户名:<input type="text" name="username"> <br>
    头像:<input type="file" name="photo"> <br>
    <input type="submit" value="上传">
</form>

Code demonstration (2): Create Servlet program upLoadServlet.java

public class upLoadServlet extends HttpServlet {
    
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        if (ServletFileUpload.isMultipartContent(request)) {
    
     
            //创建工厂实现类(FileItemFactory是一个接口,需要new其实现类)
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
    
    
                //解析上传的数据,得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(request);
                for (FileItem fileitem :
                        list) {
    
    
                    if (fileitem.isFormField()) {
    
    
                        //普通表单项
                        System.out.println("普通表单项的name属性值:" + fileitem.getFieldName());
                        //参数UTF-8,解决乱码问题
                        System.out.println("普通表单项的value属性值:" +
                                fileitem.getString("UTF-8"));
                    } else {
    
    
                        //上传的是文件类型
                        System.out.println("文件表单项的name属性值:" + fileitem.getFieldName());
                        System.out.println("上传的文件名:" + fileitem.getName());
                        //将文件写入磁盘指定的位置
                        fileitem.write(new File("e:\\" + fileitem.getName()));
                    }
                }
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

Write the corresponding servlet tag in the web.xml file

Browser running results:
Insert picture description here

Console running results:
Insert picture description here

E-disk appears:
Insert picture description here
Note: The uploaded file can be not only pictures, but also other formats

3. File download process

  1. Get the file name to download
  2. Get the file type to download
  3. Tell the client the type of file
  4. Tell the client that the data received is used for downloading
  5. Get the file to be downloaded and send it back to the client

Four, detailed explanation of the file download process

  1. Get the file name to be downloaded: Use String to define the file name to be downloaded
  2. Get the file type to be downloaded:
    through getMimeType() of ServletContext; the parameter is the path of the file to be downloaded, and the return value is String type
  3. Tell the client the type of the obtained file:
    SetContentType() of HttpServletResponse; The parameter is the result of the second step, no return value
  4. Tell the client that the data received is used for downloading (the content is directly displayed on the page without this step):
    through setHeader() of HttpServletResponse; the
    parameter is "Content-Disposition", "attachment; fileName=xxx.xxx"
    Note: The Content-Disposition response header indicates how to process the data received by the client.
    Attachment indicates the attachment, used to download the
    filename indicates the downloaded file name, which can be different from the original file name.
    This method has no return value
  5. Obtain the file to be downloaded and send it back to the client:
    send it back to the client through the copy (InputStream input, OutputStream output) of the IOUtils class of the imported io package;
    among them: ①getResourceAsStream
    () through ServletContext; The parameter is to be downloaded File path, get the input stream
    ② Get the output stream of the response through getOutputStream() of HttpServletResponse

5. The garbled problem of Chinese name download file

  1. Reason:
    response.setHeader("Content-Disposition", "attachment; fileName=中文名.jpg");
    If the downloaded file is a Chinese name, you will find that the downloaded file cannot display Chinese characters normally, because the response header cannot contain Chinese characters
  2. Solution:
    (1) When the browser is IE browser or Google browser: You
    need to use URLEncoder class to encode the Chinese name in UTF-8 first, because IE browser and Google browser will use UTF-8 after receiving the encoded string -8 character set for decoding and display, the code is as follows:
   //把中文名进行UTF-8编码操作
   URLEncoder.encode("中文名.jpg", "UTF-8");
   String str = "attachment; filename=" + URLEncoder.encode("中文名.jpg", "UTF-8");
   //把编码后的字符串设置到响应头中
   resp.setHeader("Content-Disposition", str);

(2) When the browser is Firefox: use BASE64 codec

Six, BASE64 encoding and decoding

Code demonstration: BASE64 encoding and decoding operations

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
//jdk8之后不再支持上述两个类
public class Base64Test {
    
    
    public static void main(String[] args) throws Exception {
    
    
        String content = "这是需要Base64编码的内容";
        System.out.println("初始内容:" + content);
        // 创建一个Base64编码器
        BASE64Encoder base64Encoder = new BASE64Encoder();
        // 执行Base64编码操作,encode()参数是字节数组
        String encodedString = base64Encoder.encode(content.getBytes("UTF-8"));
        System.out.println("编码后的结果:" + encodedString );
        // 创建Base64解码器
        BASE64Decoder base64Decoder = new BASE64Decoder();
        // 解码操作
        byte[] bytes = base64Decoder.decodeBuffer(encodedString);
        //以utf-8编码,以utf-8解码
        String str = new String(bytes, "UTF-8");
        System.out.println("解码后的结果:" + str);
    }
}

operation result:
Insert picture description here

Seven, the solution to the problem of garbled download files in Firefox

The Chinese name needs to be BASE64 encoded: At
this time, the request header Content-Disposition: attachment; filename=Chinese name needs to be
encoded as Content-Disposition: attachment; filename==?charset?B?xxxx?=
right=?charset?B Explanation of ?xxxxx?=:

  1. =? Indicates the beginning of the encoded content
  2. charset represents the character set (UTF-8, GBK, etc.)
  3. B means BASE64 encoding
  4. xxxx represents the content after BASE64 encoding
  5. ?= indicates the end of the encoding content

Code demo: complete file download operation

public class DownLoad extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        String downLoadFileName = "2.jpg";
        ServletContext servletContext = getServletContext();
        //斜杠代表工程路径,对应web目录
        String mimeType = servletContext.getMimeType("/File" + downLoadFileName);
        resp.setContentType(mimeType);
        //根据浏览器的不同进行不同的方式解决中文乱码
        if (req.getHeader("User-Agent").contains("Firefox")) {
    
    
            //火狐浏览器的解决方式
            resp.setHeader("Content-Disposition","attachment; filename==?UTF-8?B?"
               + new BASE64Encoder().encode("美女.jpg".getBytes("UTF-8")) + "?=");
        } else {
    
    
            //如果是IE浏览器或谷歌浏览器
            resp.setHeader("Content-Disposition","attachment; filename="
               + URLEncoder.encode("美女.jpg", "UTF-8"));
        }
        InputStream inputStream = servletContext.getResourceAsStream("/File" + downLoadFileName);
        OutputStream outputStream = resp.getOutputStream();
        IOUtils.copy(inputStream,outputStream);
    }
}

Run result:
configure in web.xml, when access to this category, it will automatically start downloading, the downloaded file name is: 美女.jpg

Guess you like

Origin blog.csdn.net/weixin_49343190/article/details/108249513