Java Spring Boot如何通过REST-API保存文本文档?

huangapple go评论65阅读模式
英文:

Java-spingboot how to save text document via REST-API?

问题

我是一名初学者程序员,需要帮忙实现通过 REST API 在 Java 中上传文本文件。

我已经实现了最简单的操作 - 从服务器卸载文件,以下是我的代码:

@GetMapping(value = "/file/{filename:.+}")
public ResponseEntity<Resource> unloadFile(@PathVariable String filename) {
    Resource file = storageService.loadAsResource(filename);
    return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
            "attachment; filename=\"" + file.getFilename() + "\"").body(file);
}

我可以通过简单地访问链接来测试文件卸载!但是我无法测试上传。我发现编写测试很困难。请告诉我是否有一个可行的代码,也许有更好的上传方式。这是我的上传代码:

@PostMapping(value = "/file")
public ResponseEntity<MultipartFile> uploadFile(MultipartFile file) {
    storageService.store(file);
    return ResponseEntity.ok().body(file);
}

非常感谢!

英文:

I am a beginner programmer, help with the implementation of uploading a text file via rest-api java.

I have already implemented the simplest action - unload a file from the server, here is my code:

@GetMapping(value = &quot;/file/{filename:.+}&quot;)
public ResponseEntity&lt;Resource&gt; unloadFile(@PathVariable String filename) {
    Resource file = storageService.loadAsResource(filename);
    return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
            &quot;attachment; filename=\&quot;&quot; + file.getFilename() + &quot;\&quot;&quot;).body(file);
}

I can test the file unload by simply following the link!
I cannot test the upload. I find it difficult to write tests. Please tell me if I got a working code and maybe there is a better way to upload. My code upload:

@PostMapping(value = &quot;/file&quot;)
public ResponseEntity&lt;MultipartFile&gt; uploadFile(MultipartFile file) {
    storageService.store(file);
    return ResponseEntity.ok().body(file);
}

Thank you so much!

答案1

得分: 0

以下是您要翻译的内容:

上传文件使用 Spring Boot 应用程序的方法与我们在 servlet 容器中使用的方法相同。在您的控制器中:

@PostMapping("/uploadFile")
public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file) {
    String fileName = yourStorageService.storeFile(file);

    String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
            .path("/downloadFile/")
            .path(fileName)
            .toUriString();
    // 您甚至可以生成下载链接。
    return new ResponseEntity<Object>("Uploaded", HttpStatus.OK, fileDownloadUri);
}

下载文件的方法:

@GetMapping("/downloadFile/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
    // 从数据库或本地加载文件作为资源
    Resource resource = fileStorageService.loadFileAsResource(fileName);

    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType(contentType))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
            .body(resource);
}
英文:

To upload the file/files using spring boot application we use same method that we had for servlet containers. In your controller

@PostMapping(&quot;/uploadFile&quot;)
    public ResponseEntity&lt;Object&gt; uploadFile(@RequestParam(&quot;file&quot;) MultipartFile file) {
        String fileName = yourStorageService.storeFile(file);

        String  = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path(&quot;/downloadFile/&quot;)
                .path(fileName)
                .toUriString();
//You can even generate download links.
        return new ResponseEntity&lt;Object&gt;(HttpStatus.Ok, &quot;Uploaded&quot;, fileDownloadUri);
    }

To download the files:

    @GetMapping(&quot;/downloadFile/{fileName}&quot;)
        public ResponseEntity&lt;Resource&gt; downloadFile(@PathVariable String fileName, HttpServletRequest request) {
            // Load file as Resource from DB or local
            Resource resource = fileStorageService.loadFileAsResource(fileName);

return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, &quot;attachment; filename=\&quot;&quot; + resource.getFilename() + &quot;\&quot;&quot;)
                .body(resource);

答案2

得分: 0

对于 @PostMapping(value = "/file") 端点,最好返回成功/错误状态,而不是返回文件,如果文件较大... 这需要时间才能返回。

最好返回成功状态,200 OK。

英文:

For @PostMapping(value = "/file") endpoint , its best to return a success/error status instead of returning the file,if file is larger ..it takes time to return back.

Better to return success state. 200 ok.

huangapple
  • 本文由 发表于 2020年8月17日 18:05:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63448661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定