multipartfile上传文件存入数据库详细代码
时间: 2023-04-04 10:04:37 浏览: 126
springmvc文件上传.docx
您好,以下是multipartfile上传文件存入数据库的详细代码示例:
@Controller
public class FileUploadController {
@Autowired
private FileStorageService fileStorageService;
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
return "redirect:/downloadFile/" + fileName;
}
}
@Service
public class FileStorageService {
@Autowired
private FileRepository fileRepository;
public String storeFile(MultipartFile file) {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
if(fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
FileEntity fileEntity = new FileEntity(fileName, file.getContentType(), file.getBytes());
fileRepository.save(fileEntity);
return fileName;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
}
public FileEntity getFile(String fileName) {
return fileRepository.findByFileName(fileName)
.orElseThrow(() -> new FileNotFoundException("File not found with name " + fileName));
}
}
@Entity
@Table(name = "files")
public class FileEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String fileName;
@Column(nullable = false)
private String fileType;
@Lob
@Column(nullable = false)
private byte[] data;
public FileEntity() {
}
public FileEntity(String fileName, String fileType, byte[] data) {
this.fileName = fileName;
this.fileType = fileType;
this.data = data;
}
// getters and setters
}
请注意,这只是一个示例代码,实际应用中可能需要根据具体情况进行修改。
阅读全文