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

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

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

}

适用于allcrud操作.

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

最佳答案
Spring Data Rest只是将Spring Data存储库公开为REST服务.支持的媒体类型是application / hal json和application / json.
您可以对Spring Data Rest进行的自定义设置如下:Customizing Spring Data REST.

如果要执行任何其他操作,则需要编写单独的控制器(以下示例来自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.";
        }
    }

}

转载注明原文:java – 有没有办法在不使用Spring-MVC的情况下使用spring-data-rest写一个rest控制器来上传文件? - 代码日志