0
My RestPictureServices Class

@Service
@TestProfile
public class RestPictureServices implements SahaPictureServices {

    @Autowired
    private PictureRepository pictureRepository;

    @Autowired
    private DozerBeanMapper mapper;

    @Override
    public Collection<SahaPicture> pictures() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public SahaPicture pictureOfSaha(Long sahaId) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public SahaPicture save(SahaPicture picture) {

        SahaPictureEntity pictureEntity=new SahaPictureEntity();
        mapper.map(picture, pictureEntity);
        pictureRepository.save(pictureEntity);
        SahaPicture savedPicture=new SahaPicture();
        mapper.map(pictureEntity, savedPicture);

        return  savedPicture;
    }

    @Override
    public Boolean delete(Long id) {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public SahaPicture update(Long id, SahaPicture picture) {
        // TODO Auto-generated method stub
        return null;
    }

}

My SahaPictureController class

@JsonRestController
@RequestMapping(path = "/saha/picture")
public class PictureController {

    @Autowired
    @Qualifier("restPictureServices")
    private SahaPictureServices pictureServices;


    @RequestMapping(method = RequestMethod.POST)
    public  SahaPicture singleSave(@RequestBody SahaPicture picture) {
        return pictureServices.save(picture);
    }

}

My PictureSahaRepository interface

 public interface PictureRepository extends CrudRepository<SahaPictureEntity,Long>  {

    }

    My picture Model class

public class SahaPicture {

    private MultipartFile file;
    //getter and setter methods   
}




    This is SahaPictureEntity class

@Entity
@Table(name="SahaPicture")

public class SahaPictureEntity {

    @Id
    @GeneratedValue
    private Long id;


    @Column
    @Lob
    private MultipartFile file;

    //getter and setter methods 

}
My JsonRestController Annotation

@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonRestController {
}

My Services Interface
public interface SahaPictureServices {


    Collection<SahaPicture> pictures();
    SahaPicture pictureOfSaha(Long sahaId);
    SahaPicture save(SahaPicture picture);
    Boolean delete(Long id);
    SahaPicture update(Long id, SahaPicture picture);
}

My Service Configuration Class using dozer mapping jar.
@Configuration
public class ServiceConfiguration {

    @Bean
    public DozerBeanMapper mapper() {
        return new DozerBeanMapper();
    }
}

How can I insert a file or an image to db with rest full services Spring boot. I am trying to restfull services to insert a file but I have got an error

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value at [Source: java.io.PushbackInputStream@21d5ad7d; line: 1, column: 3]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value at [Source: java.io.PushbackInputStream@21d5ad7d; line: 1, column: 3]

The request and response is in below picture.

enter image description here

user3233571
  • 21
  • 11

1 Answers1

0

You will want to create a REST method that includes a MultipartFile parameter. That object has a getBytes() method as well as a getInputStream() method you can use to get the data. You can then create your object and save it to the repository.

See https://spring.io/guides/gs/uploading-files/ and http://www.concretepage.com/spring-4/spring-4-mvc-single-multiple-file-upload-example-with-tomcat as good references for how to upload files with Spring .

Here is an example on the front end of how I upload a file to a REST service using jQuery.

        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");
        $.ajax({
            url: "/restapi/requests/replay/upload",
            type: "POST",
            beforeSend: function (request)
            {
                request.setRequestHeader(header,token);
            },
            data: new FormData($("#upload-file-form")[0]),
            enctype: 'multipart/form-data',
            processData: false,
            contentType: false,
            cache: false,
            success: function () {
                // Handle upload success
                addText( "File uploaded successfully.")
            },
            error: function () {
                // Handle upload error
                addText( "File upload error.")
            }
        });

Then here is what the Rest controller looks like:

@RestController
public class ReplayRestController {

@Autowired
private ApplicationContext applicationContext;

@RequestMapping(value="/restapi/requests/replay/upload", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> processUpload(
        @RequestParam("uploadfile") MultipartFile uploadfile,
        @RequestParam("databaseWriteIdUpload") String databaseWriteId,
        @RequestParam("recordsToUse")ReplayUpload.RecordsToUse recordsToUse
) {

    try {
        String fileName = uploadfile.getOriginalFilename();
        if (databaseWriteId == null || "".equals(databaseWriteId)) {
            databaseWriteId = fileName;
        }
        ReplayUpload replayUpload = applicationContext.getBean( ReplayUpload.class );
        replayUpload.process( uploadfile.getInputStream(), databaseWriteId, recordsToUse );
    }
    catch (Exception e) {
        System.out.println(e.getMessage());
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity<>(HttpStatus.OK);    }
}
Rob Baily
  • 2,770
  • 17
  • 26
  • I just want to do crud example to upload file with Rest method. I do not want to use front end to upload the file. – user3233571 Apr 25 '16 at 08:01
  • What do you mean by "I do not want to use front end to upload the file"? How are you planning on getting the data to the server? As far as I know it is not possible to upload a file without using a MultipartFile parameter. – Rob Baily Apr 26 '16 at 13:07
  • Is this more like what you are looking for? http://stackoverflow.com/questions/28179251/spring-boot-multipart-file-upload-as-part-of-json-body?rq=1 – Rob Baily Apr 26 '16 at 13:09
  • My purpose is uploading file with soap ui or postman. I was programming the rest service to upload file and insert to db. However, when I sent request body to the service with soap or postman , rest method is not working. – user3233571 Apr 27 '16 at 07:38
  • I added some code examples from what I have. I am still not certain what your issue is. I think you are trying to determine how to upload the file in a non-web client? If that is the case then presumably you have looked at this: https://www.soapui.org/rest-testing/working-with-rest-requests.html You will probably need to provide some more specific information on what is not working having debugged to see if your method is getting reached, etc. – Rob Baily Apr 28 '16 at 17:04
  • I changed code and used multipartfile obj in model class, but I got an error and the error show me could not read the file when I post the request body. What is wrong in code. – user3233571 Apr 29 '16 at 10:04
  • Can you post information on exactly how you are sending the request? If you have changed the code please update it with your latest attempt. – Rob Baily Apr 29 '16 at 13:27
  • You are still not using the MultipartFile object in your REST method. You are going to need to do that to process a file upload. To back up a little bit if you do not try to upload a file does your REST call work as planned? If not then make sure that is working before moving on to the file upload. – Rob Baily May 02 '16 at 12:24