0

I'm running a spring web application, in which at some point the user has to input about five fields in the mysql database. For every other field everything works fine, HTML's form gets the data and then spring updates the database, despite for the blob field. This blob field has to contain an image, a picture. In the model class I'm storing it with the Blob data type. This is how am asking for the picture (with the aim of bootstrap);

<!-- 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>

While this is how am receiving it with the parameters;

    @RequestParam(value = "picture", required = false) Blob picture

Then I update the database with JPA repository. But I get a 500 internal server error. This is the message;

Failed to convert value of type 'java.lang.String' to required type 'java.sql.Blob'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.sql.Blob': no matching editors or conversion strategy found

And then I get this exception;

org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.sql.Blob'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.sql.Blob': no matching editors or conversion strategy found

I would also like to specify that if I remove the picture field and I don't add it to the database everything works fine & in the MySQL Workbench I get a blank image but everything else is there.

How may I solve this? Are there better ways of storing a Blob in spring java? +Thanks everyone.

  • blol is a binary format wynot convert it to binary? – nbk Jan 23 '21 at 16:31
  • Your answer is great but I'm like a kid with spring and I don't even know what to put as data type for binary... what data type should I use? –  Jan 23 '21 at 16:33
  • for string there is longtext, but check https://stackoverflow.com/questions/42314579/convert-string-to-blob-java and https://www.mysqltutorial.org/mysql-jdbc-blob/ – nbk Jan 23 '21 at 16:41

1 Answers1

0

I am not sure why you are using Blob directly while receiving payload. You should ideally use multipart. So, your code will be like

COntroller to receive multipart file

@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);
    }
}

File handling Service class having logic to upload 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.");
        }
    }
}

Db storage service to push file to DB

@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

@Repository
public interface DBFileRepository extends JpaRepository<DBFile, String> {

}
Sridhar Patnaik
  • 970
  • 1
  • 13
  • 24