作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我已经像给定的代码一样创建了存储库
@RepositoryRestResource(collectionResourceRel = "sample", path = "/sample" )
public interface SampleRepository extends PagingAndSortingRepository<Sample, Long> {
}
适用于所有 crud 操作。
但我想创建一个上传文件的休息存储库,我将如何使用 spring-data-rest 做到这一点?
最佳答案
Spring Data Rest 只是将您的 Spring Data 存储库公开为 REST 服务。支持的媒体类型是application/hal+json
和application/json
。
此处列出了您可以对 Spring Data Rest 进行的自定义:Customizing Spring Data REST .
如果您想执行任何其他操作,您需要编写一个单独的 Controller (以下示例来自 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 Controller 来上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32067097/
我是一名优秀的程序员,十分优秀!