java - 通过postman测试上传端点

标签 java spring spring-boot postman

我正在尝试使用通过 spring 公开的端点将文件上传到我的服务器。但是,当我尝试通过 postman 测试 api 时,出现 Current request is not a multipart request 错误。我经历过这个问题MultipartException: Current request is not a multipart request但仍然无法解决这个问题。请帮忙。提前致谢。

这是我的 Controller :

@RestController
@RequestMapping
public class UploadController {

    @Autowired
    StorageService storageService;

    List<String> files = new ArrayList<String>();

    @PostMapping("/post")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        String message = "";
        try {
            storageService.store(file);
            files.add(file.getOriginalFilename());

            message = "You successfully uploaded " + file.getOriginalFilename() + "!";
            return ResponseEntity.status(HttpStatus.OK).body(message);
        } catch (Exception e) {
            message = "FAIL to upload " + file.getOriginalFilename() + "!";
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
        }
    }

    @GetMapping("/getallfiles")
    public ResponseEntity<List<String>> getListFiles(Model model) {
        List<String> fileNames = files
                .stream().map(fileName -> MvcUriComponentsBuilder
                        .fromMethodName(UploadController.class, "getFile", fileName).build().toString())
                .collect(Collectors.toList());

        return ResponseEntity.ok().body(fileNames);
    }

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

我的服务:

@Service
public class StorageService {

    Logger log = LoggerFactory.getLogger(this.getClass().getName());
    private final Path rootLocation = Paths.get("upload-dir");

    public void store(MultipartFile file) {
        try {
            Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
        } catch (Exception e) {
            throw new RuntimeException("FAIL!");
        }
    }

    public Resource loadFile(String filename) {
        try {
            Path file = rootLocation.resolve(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new RuntimeException("FAIL!");
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("FAIL!");
        }
    }

    public void deleteAll() {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }

    public void init() {
        try {
            Files.createDirectory(rootLocation);
        } catch (IOException e) {
            throw new RuntimeException("Could not initialize storage!");
        }
    }
}

正如您在下面看到的,我正在将文件作为表单数据发送,并且没有设置标题

enter image description here enter image description here

最佳答案

参见下图,并将键值添加为文件

enter image description here

关于java - 通过postman测试上传端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56556386/

相关文章:

java - 减少 Java 的操作时间

java - 关于使用MongoDB java driver的一些问题

Spring数据Mongodb : Updating documents

spring - 如何使用 Spring Batch 将 JPARepository 与 ItemReader 连接?

java - 无法从 application.yml 加载属性未绑定(bind)

java - 如何列出可用的密码算法?

java - Androidx.security 与谷歌 protobuf

java - 如何在DAO中并发使用Spring Validation Annotation(Bean Validation Specification)

java - 无法执行 Spring Boot 应用程序

Java Spring Boot 安全类配置