为什么本地调试可以下载,但部署后,不可用的原理请参考:https://www.zanglikun.com/19445.html

JD Project Excel附件 - xlsx

    @GetMapping("/download-template")
    public void downloadTemplate(HttpServletResponse httpServletResponse) throws IOException {
        InputStream inputStream = null;
        // 读取Resource下的文件 "模版.xlsx" 获取其输入流 方式1
        inputStream = new ClassPathResource("模版.xlsx").getInputStream();
        //inputStream = getClass().getResourceAsStream("/模版.xlsx"); // 读取Resource下的文件 "模版.xlsx" 获取其输入流 方式2

        // 获取输出流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        // 指定文件名,这里需要注意一下,转为ISO-8859-1,不然不支持中文作为文件名称
        String fileName = "模版" + DateUtil.now() + ".xlsx";
        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        // 指定相应信息
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        // COPY流
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        // 刷新输出流
        outputStream.flush();
        // 关闭相应的流
        outputStream.close();
        inputStream.close();
    }

GPT4 提供的更多案例!

Maven依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 其他依赖 -->
</dependencies>

代码展示

在这个FileController类中,我们定义了四个方法:

  • downloadLocalFile():从本地文件系统读取文件并作为附件下载。
  • downloadRemoteFile():从远程URL获取InputStream并将其作为附件下载到浏览器。
  • saveRemoteFileToLocal():从远程URL获取InputStream并保存到本地文件系统。
  • displayLocalFileInBrowser():从本地文件系统读取文件并直接在浏览器中显示。
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Controller
@RequestMapping("/file")
public class FileController {

    private static final String LOCAL_FILE_PATH = "path/to/your/local/file.txt"; // 本地文件路径
    private static final String REMOTE_FILE_URL = "http://example.com/file.txt"; // 远程文件URL

    @GetMapping("/download/local")
    public void downloadLocalFile(HttpServletResponse response) {
        File file = new File(LOCAL_FILE_PATH);
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName());

        try (InputStream inputStream = new FileInputStream(file);
             OutputStream outputStream = response.getOutputStream()) {
            copyStream(inputStream, outputStream);
        } catch (IOException e) {
            // Log the exception
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/download/remote")
    public void downloadRemoteFile(HttpServletResponse response) {
        try {
            URL url = new URL(REMOTE_FILE_URL);
            URLConnection connection = url.openConnection();
            try (InputStream inputStream = connection.getInputStream()) {
                response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=remoteFile.txt");
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                copyStream(inputStream, response.getOutputStream());
            }
        } catch (IOException e) {
            // Log the exception
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/save/remote")
    public ResponseEntity<String> saveRemoteFileToLocal() {
        try {
            URL url = new URL(REMOTE_FILE_URL);
            URLConnection connection = url.openConnection();
            try (InputStream inputStream = connection.getInputStream();
                 OutputStream outputStream = new FileOutputStream("savedFileName.txt")) {
                copyStream(inputStream, outputStream);
            }
            return ResponseEntity.ok("File saved successfully.");
        } catch (IOException e) {
            // Log the exception
            return ResponseEntity.internalServerError().body("Error saving file.");
        }
    }

    @GetMapping("/display/local")
    public void displayLocalFileInBrowser(HttpServletResponse response) {
        File file = new File(LOCAL_FILE_PATH);
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }

        response.setContentType(mimeType);

        try (InputStream inputStream = new FileInputStream(file)) {
            copyStream(inputStream, response.getOutputStream());
        } catch (IOException e) {
            // Log the exception
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/download/multiple")
    public void downloadMultipleFiles(HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"multiple_files.zip\"");

        String[] filesToZip = {LOCAL_FILE_PATH, "path/to/another/file.txt"}; // Replace with actual file paths

        try (ZipOutputStream zippedOut = new ZipOutputStream(response.getOutputStream())) {
            for (String filePath : filesToZip) {
                File fileToZip = new File(filePath);
                if (!fileToZip.exists()) {
                    continue;
                }
                try (FileInputStream fileInputStream = new FileInputStream(fileToZip)) {
                    ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
                    zippedOut.putNextEntry(zipEntry);
                    copyStream(fileInputStream, zippedOut);
                    zippedOut.closeEntry();
                }
            }
        } catch (IOException e) {
            // Log the exception
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    private void copyStream(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[1024];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    }
}
特殊说明:
上述文章均是作者实际操作后产出。烦请各位,请勿直接盗用!转载记得标注原文链接:www.zanglikun.com
第三方平台不会及时更新本文最新内容。如果发现本文资料不全,可访问本人的Java博客搜索:标题关键字。以获取最新全部资料 ❤