gpt4 book ai didi

java - Spring Boot上传永久文件

转载 作者:行者123 更新时间:2023-12-01 17:59:53 25 4
gpt4 key购买 nike

我正在尝试使用 Spring Boot 上传文件,但每次重新启动服务器时,我上传的文件都会消失。Spring Boot 创建名为 upload-dir 的文件,每次我重新启动服务器时,该文件都会被删除并重新创建,所以我不知道在哪里上传和存储我的文件。

我的文件上传 Controller 代码:

package com.theligue.webservice;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.theligue.webservice.storage.StorageFileNotFoundException;
import com.theligue.webservice.storage.StorageService;

import java.io.IOException;
import java.util.stream.Collectors;

@Controller
public class FileUploadController {

private final StorageService storageService;

@Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}

@GetMapping("/uploadPOC")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService
.loadAll()
.map(path ->
MvcUriComponentsBuilder
.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}





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

@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");

return "redirect:/uploadPOC/";
}

@ExceptionHandler(StorageFileNotFoundException.class)
public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) {
return ResponseEntity.notFound().build();
}

}

最佳答案

我认为您正在使用 spring boot 示例?因此,您只需在 Application.init() 中删除 storageService.deleteAll() 调用,该调用会在启动时删除所有上传的文件。

关于java - Spring Boot上传永久文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41888406/

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