Is there a way to write a rest controller to upload file using spring-data-rest without using Spring-MVC?
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.";
}
}
}
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.
}
}