当我用java从GoogleDrive下载文件时,我得到了一些符号

pobjuy32  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(408)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

16天前关门了。
改进这个问题
当我用java从GoogleDrive下载文件时,我得到的响应是这样的

这是我的密码

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();
        }
    }

你有什么建议吗?

s8vozzvw

s8vozzvw1#

我认为您的问题在于没有在http响应中设置contenttype头,因此浏览器不知道如何处理返回到响应体中的数据。为了从浏览器中获得正确的行为,您应该为返回的数据类型适当地设置contenttype头。
对于jpeg,您要调用如下内容:

response.setContentType("image/jpeg");

对于pdf,您要呼叫:

response.setContentType("application/pdf");

对于“docx”,这很奇怪,但似乎你想要的是:

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

这样做会使浏览器正确显示它知道如何显示的任何文件类型。
由于缺少任何类型信息,我认为浏览器是在将数据解释为纯文本,这就是为什么您会看到有趣的显示。
更新:根据原始海报的评论,google drive api允许通过以下调用获取下载文件的mime类型:

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

然后可以使用此值通过以下方式设置响应中的contenttype标头:

response.setContentType(mimeType);

添加这两行代码应该会导致op的代码为上传到google drive的任何类型的文件返回正确的mime类型,从而使请求的浏览器正确显示它知道如何处理的任何文件类型。

相关问题