下载文件使用spring mvc点击链接

时间:2016-08-13 12:40:53

标签: spring

When I click on any link the content should be downloaded

But this is what I get.

MastercourseController.java

@RequestMapping(value = { ControllerUriConstant.download_file }, method = RequestMethod.GET)
@ResponseBody
public void downloadingAFileById(@RequestParam("id") String id, Model model, HttpServletRequest request)
        throws TechnoShineException, IOException {
    String filePath = "D:/dev/testFIle.txt";
    long download = Long.parseLong(id);
    byte[] b = masterCourseFileFormService.getAllDownloadable(download);

    OutputStream outputStream = new FileOutputStream(filePath);
    outputStream.write(b);
    outputStream.close();

}

MasterCourseService

public byte[] getAllDownloadable(long id) throws TechnoShineException
{
    return masterCourseFormUploadDao.getAllDownloadableFiles(id);
}

MasterCourseDao

public byte[] getAllDownloadableFiles(long id) throws TechnoShineException
{
    return masterCourseFormUploadMapper.getAllDownloadable(id);

}

MasterCourseMapper

public byte[] getAllDownloadable(long id) throws TechnoShineException;

1 个答案:

答案 0 :(得分:0)

您正在将getAllDownloadable(..)返回的数据写入硬编码文件。你确定这是你想要的吗?我想你想写getAllDownloadable(..)返回的内容写入响应。这可以通过向映射添加类型HttpServletResponse的方法参数并写入HttpServletResponse#getOutputStream()返回的输出流并在末尾刷新(不关闭!)流来完成。

此外,您必须删除@ResponseBody注释,因为如果映射方法返回的值返回应直接发送到客户端的数据(即发送JSON数据时),则应使用此注释对象或字符串)而不将其传递给模板引擎。由于您没有返回任何内容,因此可以删除此注释。

此外,您必须通过调用HttpServletResponse#setContentType(contentType: String)来设置回复的内容类型。

在您的情况下,调用将如下:

response.setContentType("text/plain");

你完成的方法看起来像这样:

@RequestMapping(
    value = ControllerUriConstant.download_file,
    method = RequestMethod.GET
)
public void downloadingAFileById(@RequestParam("id") String id, HttpServletResponse response)
    throws TechnoShineException, IOException {
    long download = Long.parseLong(id);
    byte[] b = masterCourseFileFormService.getAllDownloadable(download);

    response.getOutputStream().write(b);
    response.getOutputStream().flush();
}