In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces Springboot how to export files, the article is very detailed, has a certain reference value, interested friends must read it!
Back-end code
You can set the request to post. This is Get.
@ RequestMapping (value = "/ download", method = RequestMethod.POST) public void download (HttpServletRequest request, HttpServletResponse res) throws Exception {File excelFile = new File ("/ Users/i501695/GitHUbProject/EN_ProductIntergration/databaseclient/src/main/resources/Files/ProductTemplateCopy.xlsx"); res.setCharacterEncoding ("UTF-8"); String realFileName = excelFile.getName (); res.setHeader ("content-type", "application/octet-stream;charset=UTF-8") Res.setContentType ("application/octet-stream;charset=UTF-8"); / / plus the .xlsx file downloaded by setting the size will not be reported when opened, "Excel has completed file-level verification and repair." Some parts of this workbook may have been repaired or discarded "res.addHeader (" Content-Length ", String.valueOf (excelFile.length (); try {res.setHeader (" Content-Disposition "," attachment;filename= "+ java.net.URLEncoder.encode (realFileName.trim ()," UTF-8 "));} catch (UnsupportedEncodingException E1) {e1.printStackTrace () } byte [] buff = new byte [1024]; BufferedInputStream bis = null; OutputStream os = null; try {os = res.getOutputStream (); bis = new BufferedInputStream (new FileInputStream (excelFile)); int I = bis.read (buff); while (I! =-1) {os.write (buff, 0, buff.length) Os.flush (); I = bis.read (buff);}} catch (Exception e) {e.printStackTrace ();} finally {if (bis! = null) {try {bis.close () } catch (IOException e) {e.printStackTrace () }} the front-end pseudocode is combined with Axios (the same as the core code Only combined with Axios) Axios ({/ / send post request with axios method: 'post', url:' http://127.0.0.1:8762/dataService/download', / / request address data: formData / / Parameter responseType: 'blob' / / indicates the type of data returned by the server}). Then ((res) = > {/ / process the returned file stream let blob = new Blob ([res.data], {type: res.data.type}) const fileName =' ProductTemplateCopy.xlsx' Let downloadElement = document.createElement ('a') let href = window.URL.createObjectURL (blob); / / create download link downloadElement.href = href; downloadElement.download = fileName; / / download file name document.body.appendChild (downloadElement); downloadElement.click () / Click to download document.body.removeChild (downloadElement); / / download finishes removing element window.URL.revokeObjectURL (href); / / release blob message.success ('upload successfully.');}) .catch (function (error) {console.log (error);}) Several ways of downloading SpringBoot files 1. Read the file into memory in the form of a stream at one time
Output to the front end through the response output stream
/ * * @ param path the path to the file you want to download * @ param response * @ functional description download file: * / @ RequestMapping ("/ download") public void download (String path, HttpServletResponse response) {try {/ / path refers to the path to the file you want to download File file = new File (path); log.info (file.getPath ()) / / get the file name String filename = file.getName (); / / get the file suffix String ext = filename.substring (filename.lastIndexOf (".") + 1) .toLowerCase (); log.info ("file suffix:" + ext); / / write the file to the input stream FileInputStream fileInputStream = new FileInputStream (file); InputStream fis = new BufferedInputStream (fileInputStream) Byte [] buffer = new byte [fis.available ()]; fis.read (buffer); fis.close (); / / clear response response.reset (); / / set Header response.setCharacterEncoding of response ("UTF-8") / / the function of Content-Disposition: tell the browser how to display the file returned in response, open it with the browser or download it as an attachment to the local save / / attachment to download inline as an attachment means to open "Content-Disposition: inline" online The filename= file name .mp3 "/ filename represents the default name of the file, because network transmission only supports URL-encoded related payments, so the file name needs to be encoded by URL for transmission. After receiving it, the front end needs reverse coding to get the real name response.addHeader (" Content-Disposition "," attachment;filename= "+ URLEncoder.encode (filename," UTF-8 ")). / / tell the browser the file size response.addHeader ("Content-Length", "" + file.length ()); OutputStream outputStream = new BufferedOutputStream (response.getOutputStream ()); response.setContentType ("application/octet-stream"); outputStream.write (buffer); outputStream.flush ();} catch (IOException ex) {ex.printStackTrace ();}} 2. Write the data loop from the input stream to the response output stream
Instead of reading to memory at once, output to the front end through the response output stream
/ * * @ param path refers to the path to the file you want to download * @ param response* @ function description download file: write the data in the input stream to the response output stream, instead of reading it to memory * / @ RequestMapping ("/ downloadLocal") public void downloadLocal (String path, HttpServletResponse response) throws IOException {/ / read to the stream InputStream inputStream = new FileInputStream (path); / / the path to the file response.reset () Response.setContentType ("application/octet-stream"); String filename= new File (path). GetName (); response.addHeader ("Content-Disposition", "attachment; filename=" + URLEncoder.encode (filename, "UTF-8")); ServletOutputStream outputStream = response.getOutputStream (); byte [] b = new byte [1024]; int len / / read a certain number of bytes from the input stream, store them in a buffer byte array, and return-1 while ((len = inputStream.read (b)) > 0) {outputStream.write (b, 0, len);} inputStream.close ();} 3. Download the network file to the local / * @ param path the path and name of the file after downloading * @ param netAddress file * @ function description network file is downloaded to the server local * / @ RequestMapping ("/ netDownloadLocal") public void downloadNet (String netAddress, String path) throws IOException {URL url = new URL (netAddress); URLConnection conn = url.openConnection (); InputStream inputStream = conn.getInputStream () FileOutputStream fileOutputStream = new FileOutputStream (path); int bytesum = 0; int byteread; byte [] buffer = new byte [1024]; while ((byteread = inputStream.read (buffer))! =-1) {bytesum + = byteread; System.out.println (bytesum); fileOutputStream.write (buffer, 0, byteread) } fileOutputStream.close ();} 4. After the network file is obtained to the server
The response is sent to the front end after being processed by the server.
/ * @ param netAddress * @ param filename * @ param isOnLine * @ param response * @ function describes that after the network file is obtained from the server, the response is sent to the front end * / @ RequestMapping ("/ netDownLoadNet") public void netDownLoadNet (String netAddress, String filename, boolean isOnLine, HttpServletResponse response) throws Exception {URL url = new URL (netAddress); URLConnection conn = url.openConnection (); InputStream inputStream = conn.getInputStream (); response.reset () Response.setContentType (conn.getContentType ()); if (isOnLine) {/ / online open file name should be encoded as UTF-8 response.setHeader ("Content-Disposition", "inline; filename=" + URLEncoder.encode (filename, "UTF-8"));} else {/ / download-only file name should be encoded as UTF-8 response.setHeader ("Content-Disposition", "attachment") Filename= "+ URLEncoder.encode (filename," UTF-8 ");} byte [] buffer = new byte [1024]; int len; OutputStream outputStream = response.getOutputStream (); while ((len = inputStream.read (buffer)) > 0) {outputStream.write (buffer, 0, len);} inputStream.close ();} 5. Common exceptions and problems (1) the response object does not need to be returned through return
Reason: the response object can not be returned as a method return value, it has already started to be output when the method is executed, and it cannot be returned to the front end in JSON format with @ RestController
Solution: delete the return statement
(2) the file name returned to the front end must be URL encoded
Reason: network transmission can only transmit dozens of specific characters, and Chinese characters and special characters need to be encoded by Base64 to convert them into specific characters, so that they can be transmitted without garbled codes.
URLEncoder.encode (fileName, "UTF-8") (3) IO streams need to be learned
1:read ():
Reads the next byte of the data from the input stream and returns an int byte value in the range of 0 to 255. If no bytes are available because the end of the stream has been reached,-1 is returned. This method blocks until the input data is available, the end of the stream is detected, or an exception is thrown.
2:read (byte [] b):
Reads a certain number of bytes from the input stream and stores them in the buffer array b. Returns the number of bytes actually read as an integer. This method blocks until the input data is available, the end of the file is detected, or an exception is thrown. If the length of b is 0, no bytes are read and 0 is returned; otherwise, try to read at least one byte. If no bytes are available because the stream is at the end of the file, the value is-1
The above is all the contents of the article "how to export files from Springboot". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.