在 Spring 引导中下载动态 XML/JSON 文件
Download dynamic XML/JSON file in Spring Boot
我需要实现一项功能,让用户可以下载他们的XML或JSON格式文件[=21]他们的个人数据=].
该文件将在 运行 时间生成,我不知道如何在 Spring 引导中在我的应用程序的相应 @RestController
中实现它。
到目前为止,我只实现了创建适当的 XML 或 JSON 字符串,起初我想将其作为响应发送,让前端管理其余部分,但我认为这不是解决问题的方法,因为需要下载文件。
由于您的文件是从字符串动态创建的,因此您需要创建一个输出流并将字符串内容写入其中。我没有测试过这些,但我过去使用过类似的代码。
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RequestMapping("/downloadDocument")
public void downloadDocument(HttpServletResponse response, HttpServletRequest request) throws IOException {
//jsonPersonal is the string that you're going to create dynamically in your code
final String jsonPersonal = " some json encoded data here";
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Transfer-Encoding", "binary");
response.setContentType("application/json");
response.setContentLength( jsonPersonal.length());
response.setHeader("Content-Disposition", "attachment");
//this copies the content of your string to the output stream
IOUtils.copy(IOUtils.toInputStream(jsonPersonal), response.getOutputStream());
response.flushBuffer();
}
我需要实现一项功能,让用户可以下载他们的XML或JSON格式文件[=21]他们的个人数据=].
该文件将在 运行 时间生成,我不知道如何在 Spring 引导中在我的应用程序的相应 @RestController
中实现它。
到目前为止,我只实现了创建适当的 XML 或 JSON 字符串,起初我想将其作为响应发送,让前端管理其余部分,但我认为这不是解决问题的方法,因为需要下载文件。
由于您的文件是从字符串动态创建的,因此您需要创建一个输出流并将字符串内容写入其中。我没有测试过这些,但我过去使用过类似的代码。
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RequestMapping("/downloadDocument")
public void downloadDocument(HttpServletResponse response, HttpServletRequest request) throws IOException {
//jsonPersonal is the string that you're going to create dynamically in your code
final String jsonPersonal = " some json encoded data here";
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Transfer-Encoding", "binary");
response.setContentType("application/json");
response.setContentLength( jsonPersonal.length());
response.setHeader("Content-Disposition", "attachment");
//this copies the content of your string to the output stream
IOUtils.copy(IOUtils.toInputStream(jsonPersonal), response.getOutputStream());
response.flushBuffer();
}