Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to write a rest controller to upload file using spring-data-rest without using Spring-MVC?

I have created repository like given code

@RepositoryRestResource(collectionResourceRel = "sample", path = "/sample" )
public interface SampleRepository extends PagingAndSortingRepository<Sample, Long> {

}

works fine for allcrud operations.

But I wanted to create a rest repository which upload file, How i would do that with spring-data-rest?

like image 338
Manish Carpenter Avatar asked Aug 18 '15 08:08

Manish Carpenter


People also ask

Can we upload file using REST API?

You can use this parameter to set metadata values to a collection already assigned to any parent folder. The rules are the same as those applied to the set metadata values REST API. Use Content-Type: application/json to describe this information as a JSON object. File to upload.

Can we use REST controller in spring MVC?

Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON or XML response.


2 Answers

Spring Data Rest simply exposes your Spring Data repositories as REST services. The supported media types are application/hal+json and application/json.

The customizations you can do to Spring Data Rest are listed here: Customizing Spring Data REST.

If you want to perform any other operation you need to write a separate controller (following example from Uploading Files):

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController {

    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file){
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + "!";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

}
like image 120
Francesco Pitzalis Avatar answered Oct 23 '22 23:10

Francesco Pitzalis


Yes you can try this:

@RestController
@EnableAutoConfiguration
@RequestMapping(value = "/file-management")
@Api(value = "/file-management", description = "Services for file management.")
public class FileUploadController {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(FileUploadController.class);
    @Autowired
    private StorageService storageService;  //custom class to handle upload.
    @RequestMapping(method = RequestMethod.POST, headers = ("content-    type=multipart/*"), produces = "application/json", consumes =            MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.CREATED)
    public void handleFileUpload(
            @RequestPart(required = true) MultipartFile file) {
        storageService.store(file);  //your service to hadle upload.
    }
}
like image 32
Ravindra Kumar Avatar answered Oct 24 '22 01:10

Ravindra Kumar