The essence of uploading and downloading various files

 

upload files

1, the file is converted into a stream, and the stream is converted into a file

2. Parse the file, the file parsing class of the corresponding format, parse the file stream, and obtain the data in the file stream. On the contrary, java generates the corresponding stream and uses the corresponding file parser to generate the file

 

eg excl

 XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is.getInputStream());

 

 // Create a writable Excel workbook

 jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File("C:/temp/"+is.getOriginalFilename()));

 

 

picture:

Page directly <img src="" />

 

 

 

download:

 

The file becomes a stream response back to the page, 

//2. Set the file header: the last parameter is to set the download file name (if we call it a.pdf) (including the suffix)

response.setHeader("Content-Disposition", "attachment;fileName="+fileUrl);

 

 

 

 

 

@RequestMapping(value = "/downLoad")

    public String getObject(@RequestParam("fileUrl") String fileUrl,HttpServletRequest req, HttpServletResponse resp) throws Exception {

        InputStream is = new FileInputStream(fileUrl);

        HttpServletResponse response = resp;

        ServletOutputStream out = null;

        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();

        try {

 

            byte[] buf = new byte[16384];

            int bytesRead;

            while ((bytesRead = is.read(buf, 0, buf.length)) >= 0) {

                swapStream.write(buf, 0,bytesRead);

            }

 

            // Close the input stream.

            is.close();

            byte[] in_b = swapStream.toByteArray();

            response.setContentType("multipart/form-data");

            //2. Set the file header: the last parameter is to set the download file name (if we call it a.pdf)

            response.setHeader("Content-Disposition", "attachment;fileName="+fileUrl);

            out = response.getOutputStream();

            out.write(in_b);

            out.flush();

        } catch (Exception e) {

            e.printStackTrace ();

        } finally {

            swapStream.close();

            if (out != null) {

                try {

                    out.close();

                } catch (Exception e) {

                    e.printStackTrace ();

                }

            }

            if (response != null) {

                try {

                    response.flushBuffer();

                } catch (Exception e) {

                    e.printStackTrace ();

                }

            }

        }

        return null;

    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326059525&siteId=291194637