Как скачать BLOB из MySQL, используя Spring MVC framework

0

Я создал код для загрузки файла PDF в BLOB базы данных MySQL.

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>

Пружинный контроллер:

@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 файл в поле BLOB-объектов таблицы MySQL. Но я не знаю, как получить данные BLOB-объекта в виде гиперссылки, где я могу щелкнуть ссылку и загрузить файл PDF. Пожалуйста, помогите мне.

Теги:
spring-mvc
hibernate
blob

1 ответ

1
Лучший ответ

Вы можете попробовать извлечь содержимое документа из 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";
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню