有没有办法在不使用Spring-MVC的情况下使用spring-data-rest写一个rest控制器来上传文件?

Man*_*ish 9 java spring spring-data-rest

我创建了像给定代码一样的存储库

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

}
Run Code Online (Sandbox Code Playgroud)

适用于allcrud操作.

但我想创建一个上传文件的休息库,如何用spring-data-rest做到这一点?

Fra*_*lis 10

Spring Data Rest只是将Spring Data存储库公开为REST服务.支持的媒体类型是application/hal+jsonapplication/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.";
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 仅当您要覆盖Spring Data REST自动生成的控制器的默认行为时,才应显式使用`@RepositoryRestController`.有关详细信息,请查看[此处](http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlers). (2认同)