下载文件 单击使用弹簧 mvc 的链接



当我点击任何链接时,应该下载内容

但这就是我得到的。


硕士课程控制器.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();
}

硕士课程服务

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

大师课程道

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

MasterCourseMapper

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

您正在将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();
}

最新更新