如何使用springmvc框架从mysql下载blob

ubof19bj  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(381)

我已经创建了将pdf文件上传到mysql数据库blob的代码。
html代码:

<form method="post" action="doUpload" enctype="multipart/form-data">
    <table border="0">
        <tr>
            <td>Pick file #1:</td>
            <td><input type="file" name="fileUpload" size="50" /></td>
        </tr>
        <tr>
             <td colspan="2" align="center"><input type="submit" value="Upload" /></td>
        </tr>
     </table>
</form>

Spring控制器:

@RequestMapping(value = "/doUpload", method = RequestMethod.POST)
public String handleFileUpload(HttpServletRequest request,
        @RequestParam CommonsMultipartFile[] fileUpload) throws Exception {

    if (fileUpload != null && fileUpload.length > 0) {
        for (CommonsMultipartFile aFile : fileUpload) {
            System.out.println("Saving file: " + aFile.getOriginalFilename());
            UploadFile uploadFile = new UploadFile();
            uploadFile.setFileName(aFile.getOriginalFilename());
            uploadFile.setData(aFile.getBytes());
            fileUploadDao.save(uploadFile);                
        }
    }
    return "Success";
}

我可以将pdf文件上传到mysql表的blob字段中。但我不知道如何检索blob数据,作为一个超链接,在那里我可以单击链接并下载pdf文件。请帮帮我。

bjg7j2ky

bjg7j2ky1#

您可以尝试从mysql获取文档内容,然后在 response 对象。
使用 response.setHeader() 要设置的方法 "Content-Disposition" 将在浏览器中启动“另存为”对话框,供用户下载文件。

@RequestMapping("/retrieve/{fileName}")
public String download(@PathVariable("fileName")
        String fileName, HttpServletResponse response) {

    DownloadFile downloadDocument = downloadFileDao.get(fileName);
    try {
        response.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
        OutputStream out = response.getOutputStream();
        response.setContentType(downloadDocument.getContentType());
        IOUtils.copy(downloadDocument.getContent().getBinaryStream(), out);
        out.flush();
        out.close();

    } catch (SQLException e) {
        System.out.println(e.toString());
        //Handle exception here
    } catch (IOException e) {
        System.out.println(e.toString());
        //Handle exception here
    }

    return "Success";
}

相关问题