当我使用 java 从 google 驱动器下载文件时,我得到了符号

when I downloading file from google drive with java i get symbols

当我使用 java 从 google 驱动器下载文件时,我得到类似图片中的响应

有我的代码

public void downloadFile(String fileId, OutputStream outputStream) {
        if (fileId != null) {
            try {
                googleDriveService.getInstance().files()
                    .get(fileId).executeMediaAndDownloadTo(outputStream);
            } catch (IOException | GeneralSecurityException e) {
                e.printStackTrace();
            }
        }
    }

还有我的控制器

@GetMapping("/download/{fileId}")
    public void download(@PathVariable String fileId, HttpServletResponse response) {
        try {
            documentService.downloadFile(fileId, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

你有什么建议吗?

我认为您的问题是您没有在 HTTP 响应中设置 ContentType header,因此您的浏览器不知道如何处理响应中返回的数据 body。要从您的浏览器中获得正确的行为,您应该根据您正在 return 使用的数据类型适当地设置 ContentType header。

对于 JPEG,您想调用如下内容:

response.setContentType("image/jpeg");

对于 PDF,您要调用:

response.setContentType("application/pdf");

对于“docx”,有点奇怪,不过好像你要的是:

response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");

这样做应该会使您的浏览器正确显示它知道如何显示的任何文件类型。

由于缺少任何类型信息,我相信浏览器会将数据解释为纯文本,这就是为什么您看到的显示很有趣。

更新:根据原始发帖人的评论,Google 驱动器 API 允许通过调用获取下载文件的 MIME 类型:

String mimeType = googleDriveService.getInstance().files().get(fileId).execute().getMimeType();

此值随后可用于在响应中设置 ContentType header,通过:

response.setContentType(mimeType);

添加这两行代码应该会导致 OP 的代码 return 上传到 Google 驱动器的任何类型文件的正确 MIME 类型,从而使请求浏览器正确显示它知道如何处理的任何文件类型。