2021-10-14 ContextType (MIME) and Java file upload / download

ContextType(MIME)

ContextType is a field in which MIME (Multipurpose Internet Mail Extensions) represents the type of information transmitted over HTTP. Different contexttypes represent different types. There are some commonly used contexttypes.

The syntax of MIME type is type/subtype, which is in IETF RFC 6838 The syntax is composed of top-level types and subtypes, with a '/' in the middle. For example, text/html represents the text type of html

Text

Texttop level type is used to send content, mainly in text form

Common types:

  • text/plain: plain text format, which is a generic subtype of plain text
  • text/html: HTML format
  • text/xml: XML format

Image

The image top-level type indicates that the content specifies more than one single image, and the subtype is a specific image naming format

Common types:

  • image/gif: gif picture format
  • image/jpeg: jpg picture format
  • image/png: png picture format

Audio

The audio top-level type indicates that the content contains audio data, and the subtype names a specific audio format

Video

The top-level type of video indicates that the content specifies a video (an image that changes over time) and may have color and coordinated sound. More specifically, the word "video" is used in its most general sense rather than referring to any specific technology or format. It does not exclude subtypes, such as encoded animation.

Application

application top-level type common path type names include but are not limited to the forms of file transfer, spreadsheet, presentation, scheduling data and "activity" language (calculation)

Common types:

  • application/xhtml+xml: XHTML format
  • application/xml: XML data format
  • application/atom+xml: Atom XML aggregation format
  • application/json: JSON data format
  • application/pdf: pdf format
  • application/msword: Word document format
  • Application / octet stream: binary stream data (such as common file download)
  • application/x-www-form-urlencoded: the default encType in the form. The form data is encoded as key/value format and sent to the server (the default format of the form submission data)

Multipart and Message

multipart and message are composite types, that is, they provide methods to encapsulate zero or more objects, each of which is an independent media type.

All subtypes of multipart and message must comply with the syntax rules and other requirements specified in [RFC 2046], as amended by section 3.5 of [RFC 6532].

  • Multipart / form data: this format is required when uploading files in the form

Upload / download

Handle file upload / download Java code

upload

    /**
     * File upload uses third-party jar packages: commons file upload and Commons io
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ReturnEntity returnEntity = null;
        //Judge whether it is multi segment data
        if (ServletFileUpload.isMultipartContent(req)) {
            //Create the FIleItemFactory factory implementation class
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //Create a tool class ServletFileUpload class for parsing uploaded data
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            //Analyze the uploaded data to get the form items
            try {
                List<FileItem> fileItems = servletFileUpload.parseRequest(req);
                for (FileItem fileItem : fileItems) {
                    System.out.println(fileItem);
                    if (fileItem.isFormField()){
                        System.out.println("name Value:" + fileItem.getFieldName());
                        System.out.println("value Value:" + fileItem.getString("UTF-8"));
                    } else {
                        System.out.println("name Value:" + fileItem.getFieldName());
                        System.out.println("value Value:" + fileItem.getName());
                        fileItem.write(new File(getServletContext().getRealPath("/")+fileItem.getName()));
                        returnEntity = new ReturnEntity(CodeStatus.UPLOAD_SUCCESS.getCode(), CodeStatus.UPLOAD_SUCCESS.getMsg(), null);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                returnEntity = new ReturnEntity(CodeStatus.UPLOAD_FAILED.getCode(), CodeStatus.UPLOAD_FAILED.getMsg(), null);
            }
        } else {
            returnEntity = new ReturnEntity(CodeStatus.UPLOAD_FAILED.getCode(), CodeStatus.UPLOAD_FAILED.getMsg(), null);
        }
        // Return results
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        try {
            writer.write(JSON.toJSONString(returnEntity));
        } finally {
            writer.flush();
            writer.close();
        }
    }

download

	/**
     * File download
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void download(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get request resource path
        String filePath = req.getParameter("filePath");
        //Get Servlet upper bound text
        ServletContext servletContext = getServletContext();
        //Gets the file type to download
        String mimeType = servletContext.getMimeType(filePath);
        System.out.println("mimeType = " + mimeType);
        //Before returning, the client is informed of the returned data type through the response header
        resp.setContentType(mimeType);
        //Tell the client that the data received is for download (through the response header)
        if (req.getHeader("User-Agent").contains("Firefox")) {
            //Firefox Base64
            resp.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" + new BASE64Encoder().encode(filePath.getBytes("UTF-8")) + "?=");
        } else {
            //Google IE URLEncoder
            resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filePath, "UTF-8"));
        }
        //Get transport file stream
        InputStream resourceAsStream = servletContext.getResourceAsStream(filePath);//The file path to be uploaded obtains resources from the project directory
        //Gets the returned output stream
        ServletOutputStream outputStream = resp.getOutputStream();
        //output file
        try {
            byte[] data = new byte[1024 * 8];
            int len = 0;
            while ((len = resourceAsStream.read(data)) != -1) {
                outputStream.write(data, 0, len);
            }
        } finally {
            resourceAsStream.close();
            outputStream.flush();
            outputStream.close();
        }
//        IOUtils.copy(resourceAsStream, outputStream); //  Third party jar package: commons-io-2.11.0.jar
        System.out.println("download '" + filePath + "' completion");
    }

Keywords: Java html5 html http

Added by gszauer on Fri, 15 Oct 2021 00:10:53 +0300