Here is an example code for you to use Response to download files.
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1.Get the file path String realPath = "D:\\project\\\servlet-main\\\\response\\\src\\\main\\\resources\\\\avatar.jpg"; // 2. Get the file name String fileName = realPath.substring(realPath.lastIndexOf("\\\") + 1); // 3. Set the request header (Content-Disposition of the header to support file download) resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 4. Get the input stream of the downloaded file: FileInputStream FileInputStream inputStream = new FileInputStream(realPath); // 5. Create buffer int length = 0; byte[] buffer = new byte[1024]; // 6. Get the input stream object: OutputStream ServletOutputStream outputStream = resp.getOutputStream(); // 7. Write the stream to the buffer and use the OutputStream to output the data in the buffer to the client while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); }
Read More:
- How to Solve IBM MQ Connect Error Code 2035
- [Solved] java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
- How to Solve The classpathresource reads the resource file Error
- How to Use filechannel to copy files
- Idea unified setting code to UTF-8 code and solution of Tomcat garbled code
- [Solved] cannot call sendError() after the response has been committed
- [Solved] Default native-compiler executable ‘cl.exe‘ not found via environment variable PATH
- How to Solve SSM JSON Chinese Messy Code Issue
- Multipartfiletofileutils (multipartfile to file)
- [Solved] You must configure either the server or JDBC driver (via the ‘serverTimezone‘ configuration proper
- Flutter: How to Fix Android module can’t recognize flutter SDK source code
- Java will convert Excel to list set or JSON, export excel file to local, excel import and export, easyexcel tool class
- [Solved] springsecurity custom exceptions: Error: Parse Error: Response overflow
- Cannot call sendRedirect() after the response has been committed
- How to Solve Springboot configurate environment file Error
- How to Solve Java Runtime (class file version 53.0)ERROR
- Solve the problem that some jar packages failed to download when Maven was packaged
- Eclipse: How to Close XML validation (xml file Error)
- [Solved] Cannot call sendError() after the response has been committed
- How to Solve Image Upload Error: Uncaught (in promise) DOMException: Failed to execute ‘put‘ on ‘IDBObjectStore‘