java 如何将 byte[] 转换为带有下载对话框的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13989215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:39:46  来源:igfitidea点击:

How to convert a byte[] into a file with a download dialog box?

javaspringspring-mvc

提问by Freakyuser

I have a table with blob content in it, in which I store different file types(text, audio, image, etc). After retrieving the byte []successfully, I don't have any idea of how to convert the [] in such a way as to convert it into a download dialog box.
Here is my code

我有一个包含 blob 内容的表,我在其中存储了不同的文件类型(text, audio, image, etc)byte []成功检索后,我不知道如何将[]转换为将其转换为下载对话框。
这是我的代码

trns = session.beginTransaction();
Query query = session.createQuery("from FileDownload as fu where fu.Id =:Id");
query.setInteger("Id", id);
FileDownload fileDownload = (FileDownload) query.iterate().next();
byte[] byteArray = fileDownload.getFile();

The above code works fine and I receive a byte []. But I don't know how to proceed further in order to convert it into a file with the dialog appearing.

上面的代码工作正常,我收到一个byte []. 但我不知道如何进一步将其转换为出现对话框的文件。

Can anyone please help me?

谁能帮帮我吗?

回答by Moritz Petersen

Assuming you know the mimeTypeand filenameof your file, you can set the content type and the HTTP header Content-Disposition.

假设您知道文件的mimeTypefilename,您可以设置内容类型和 HTTP 标头 Content-Disposition。

Just write the byte array to the OutputStream:

只需将字节数组写入OutputStream

    // The response from your servlet.
    HttpServletResponse resp;
    resp.setContentType(mimeType);
    resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
    resp.getOutputStream().write(byteArray);

回答by Sean Connolly

The byte array can be sent to the client from a servlet. You can find many discussions on the topic here and elsewhere.

字节数组可以从 servlet 发送到客户端。您可以在此处和其他地方找到有关该主题的许多讨论。

Here are folks discussing efficiency of streaming(with code). Here is a discussion on how to map the servlet to a url(with examples).

这里有人在讨论流的效率(带代码)。这里讨论如何将 servlet 映射到 url(带有示例)。

The last thing for you to do is just link the user to the servlet's URL when they click the button.

您要做的最后一件事就是在用户单击按钮时将用户链接到 servlet 的 URL。

You'll also want to look into what additional info you can provide in the header before streaming the byte array. For example, if you provide a mime type the browser then has a clue what to do with the file; open PDFs in the browser, display images in the browser; open xls files in Excel.

在流式传输字节数组之前,您还需要查看可以在标头中提供哪些附加信息。例如,如果您提供 MIME 类型,浏览器就会知道如何处理该文件;在浏览器中打开PDF,在浏览器中显示图片;在 Excel 中打开 xls 文件。