Spring Boot+MSSQL文件下载损坏问题技术求助
问题:Spring Boot文件下载后损坏
我正在使用Spring Boot、JSP和MSSQL开发文件上传下载功能,目前上传和下载流程可正常运行,但从数据库下载的文件出现损坏情况。原TXT文件内容应为:
testing123
abc
技术信息
Spring版本
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.0.3-SNAPSHOT</version> <relativePath /> <!-- lookup parent from repository --> </parent>
控制器代码
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public ResponseEntity<Object> upload(@RequestPart(required = false) MultipartFile file) throws IOException { try { if (file != null) { tmDAO.storeFile(file, tm); } return new ResponseEntity<>("success", HttpStatus.OK); } catch (Exception e) { System.out.println(e.getMessage()); } } @RequestMapping("/downloadFile/{id}") public String downloadFile(@PathVariable("id") String id, HttpServletResponse res) throws IOException { FileModel fm = tmDAO.getFile(id); try { File file = new File(fm.getName()); FileOutputStream fos = new FileOutputStream(file); res.setContentLength(fm.getData().length); res.setHeader("Content-Disposition", "attachment; filename=" + fm.getName()); fos.write(fm.getData(), 0, fm.getData().length); fos.flush(); fos.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return "string"; }
服务层代码
@Override public FileModel storeFile(MultipartFile file, TeachingMaterial tm) throws IOException { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); FileModel fileModel = new FileModel(UUID.randomUUID().toString(), tm.getContributor(), fileName, file.getContentType(), file.getBytes(), tm.getClassName(), tm.getSubjectName(), tm.getSlots()); return fileRepo.save(fileModel); } @Override public FileModel getFile(String id) throws IOException { Optional<FileModel> fm = fileRepo.findById(id); if (fm.isPresent()) { return fm.get(); } return null; }
实体类FileModel.java代码
@Entity @Table(name = "FILES") public class FileModel { @Id private String id; private String contributor; private String name; private String type; @Lob private byte[] data; private String className; private String subjectName; private String slots; public FileModel() { super(); } public FileModel(String id, String contributor, String name, String type, byte[] data, String className, String subjectName, String slots) { super(); this.id = id; this.contributor = contributor; this.name = name; this.type = type; this.data = data; this.className = className; this.subjectName = subjectName; this.slots = slots; } // 省略getter和setter }
恳请技术人士帮忙解决文件下载损坏的问题。
内容的提问来源于stack exchange,提问作者Zaydon Lim
相关产品推荐
相关产品推荐

