Есть ли способ написать контроллер rest для загрузки файла с помощью spring-data-rest без использования Spring-MVC?

Я создал репозиторий, как данный код

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

}

отлично работает для операций allcrud.

но я хотел создать репозиторий rest, который загружает файл, Как бы я это сделал с spring-data-rest?

2 ответов


Spring Data Rest просто предоставляет ваши хранилища данных Spring как службы REST. Поддерживаемые типы носителей application/hal+json и application/json.

настройки, которые вы можете сделать для Spring Data Rest, перечислены здесь:настройка Spring Data REST.

Если вы хотите выполнить любую другую операцию, вам нужно написать отдельный контроллер (следующий пример из Загрузка Файлов):

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.";
        }
    }

}

Да, вы можете попробовать это:

@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.
    }
}