【问题标题】:Test upload endpoint through postman通过邮递员测试上传端点
【发布时间】:2019-10-26 14:59:36
【问题描述】:

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

这是我的控制器:

@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!");
        }
    }
}

正如您在下面看到的,我正在以表单数据的形式发送文件,并且没有设置任何标题

【问题讨论】:

  • 使用键的字段=文件
  • 也为这个问题添加标签 spring,让更多的观众看到这个

标签: java spring spring-boot postman


【解决方案1】:

尝试在您的请求标头中添加Content-Type: multipart/form-data(据我在邮递员中看到它丢失了)

【讨论】:

    【解决方案2】:

    您的控制器需要一个请求参数“文件”:

    @RequestParam("file") MultipartFile file
    

    您必须在邮递员中设置键“文件”,其中值是您的文件(最后一个屏幕截图)。

    【讨论】:

      【解决方案3】:

      如下图所示,添加键值为file

      【讨论】:

        猜你喜欢
        • 2016-09-17
        • 2020-06-30
        • 2021-01-15
        • 1970-01-01
        • 2023-01-09
        • 2021-10-26
        • 2019-01-08
        • 2020-06-19
        • 1970-01-01
        相关资源
        最近更新 更多