gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:12:57 24 4
gpt4 key购买 nike

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

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

}

适用于所有 crud 操作。

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

最佳答案

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com