我正在运行一个spring web应用程序,在这个应用程序中,用户必须在mysql数据库中输入大约五个字段。对于每个其他字段,一切正常,HTML的表单获取数据,然后spring更新数据库,尽管使用的是blob字段。这个blob字段必须包含一个图像,一张图片。在model类中,我使用Blob数据类型存储它。这就是我请求图片的方式(目的是引导);
<!-- Picture -->
<div class="custom-file">
<input type="file" class="custom-file-input" name="picture">
<label class="custom-file-label" for="picture">Select picture...</label>
</div>而这就是我如何通过参数接收它;
@RequestParam(value = "picture", required = false) Blob picture然后,我使用JPA存储库更新数据库。但是我得到了一个500内部服务器错误。这就是信息;
未能将'java.lang.String‘类型的值转换为所需的类型'java.sql.Blob';嵌套异常为java.lang.IllegalStateException:无法将'java.lang.String’类型的值转换为所需的类型'java.sql.Blob':找不到匹配的编辑器或转换策略
然后我得到了这个异常;
org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException:无法将'java.lang.String‘类型的值转换为所需的类型'java.sql.Blob';嵌套异常为java.lang.IllegalStateException:无法将'java.lang.String’类型的值转换为所需的类型'java.sql.Blob':找不到匹配的编辑器或转换策略
我还想指定,如果删除图片字段,并且不将其添加到数据库中,则一切正常&在MySQL工作台中,我得到一个空白图像,但其他所有内容都在那里。
我该如何解决这个问题呢?在spring java中有没有更好的存储Blob的方法?+谢谢大家。
发布于 2021-01-24 01:59:23
我不确定为什么在接收有效负载时要直接使用Blob。理想情况下,您应该使用multipart。因此,您的代码将如下所示
接收多部分文件的COntroller
@RestController
@RequestMapping("/file")
public class FileHandlingController
{
@Autowired
FileHandlingService fileHandlingSgervice;
@PostMapping(value = "/upload")
@ResponseStatus(HttpStatus.ACCEPTED)
public FileInformation uploadDoc(@RequestParam("file") MultipartFile file) throws Exception
{
return fileHandlingSgervice.uploadDoc(file);
}
}具有上传文件的逻辑的文件处理服务类
@Service
public class FileHandlingService
{
@Autowired
DBFileStorageService dbFileStorageService;
public FileInformation uploadDoc(MultipartFile file) throws Exception
{
try
{
FileInformation fileUploadSuccessData = new FileInformation();
DBFile dbFile = dbFileStorageService.storeFile(file);
fileUploadSuccessData.setFileUUId(dbFile.getId());
fileUploadSuccessData.setFileName(dbFile.getFileName());
return fileUploadSuccessData;
}
catch(MaxUploadSizeExceededException e)
{
throw new Exception("File size too large. Max allowed size - 15 MB");
}
catch(Exception e)
{
throw new Exception("Error uploading file.");
}
}
}数据库存储服务,用于将文件推送到数据库
@Service
public class DBFileStorageService {
@Autowired
private DBFileRepository dbFileRepository;
public DBFile storeFile(MultipartFile file) {
// Normalize file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Check if the file's name contains invalid characters
if(fileName.contains("..")) {
//throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
DBFile dbFile = new DBFile(fileName, file.getContentType(), file.getBytes());
return dbFileRepository.save(dbFile);
} catch (IOException ex) {
//throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
return null;
}
}存储库
@Repository
public interface DBFileRepository extends JpaRepository<DBFile, String> {
}https://stackoverflow.com/questions/65861412
复制相似问题