文件未保存到目录

时间:2019-08-11 20:45:49

标签: java spring file

我想使用此代码将文件上传到Spring后端。

private static String UPLOADED_FOLDER = "/opt";

    @PostMapping(value = "/upload", produces = { MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<StringResponseDTO> uploadData(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws Exception {

        if (file == null) {
            throw new RuntimeException("You must select the a file for uploading");
        }

        InputStream inputStream = file.getInputStream();
        String originalName = file.getOriginalFilename();
        String name = file.getName();
        String contentType = file.getContentType();
        long size = file.getSize();

        LOG.info("inputStream: " + inputStream);
        LOG.info("originalName: " + originalName);
        LOG.info("name: " + name);
        LOG.info("contentType: " + contentType);
        LOG.info("size: " + size);

        try {

            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(new StringResponseDTO(originalName));
    }

由于某种原因,文件未保存到/ opt目录中。您能给我一些建议,为什么代码无法正常工作。

进入我得到的日志文件:

2019-08-11 20:40:36,297 INFO  [stdout] (default task-17) 20:40:36.297 [default task-17] INFO  o.d.a.b.restapi.MerchantController - inputStream: java.io.BufferedInputStream@661c793f
2019-08-11 20:40:36,298 INFO  [stdout] (default task-17) 20:40:36.298 [default task-17] INFO  o.d.a.b.restapi.MerchantController - originalName: Screenshot 2019-07-14 at 14.33.41.png
2019-08-11 20:40:36,299 INFO  [stdout] (default task-17) 20:40:36.298 [default task-17] INFO  o.d.a.b.restapi.MerchantController - name: file
2019-08-11 20:40:36,299 INFO  [stdout] (default task-17) 20:40:36.299 [default task-17] INFO  o.d.a.b.restapi.MerchantController - contentType: image/png
2019-08-11 20:40:36,300 INFO  [stdout] (default task-17) 20:40:36.300 [default task-17] INFO  o.d.a.b.restapi.MerchantController - size: 20936

1 个答案:

答案 0 :(得分:2)

请尝试执行以下操作,而不要使用Paths#get

File newFile = new File(UPLOADED_FOLDER, file.getOriginalFileName());
LOG.info("New file location: " + newFile.getAbsolutePath()); //Log the path
Files.write(newFile.toPath(), bytes);

与其使用+运算符来对String进行排序以创建新文件的路径,最好使用java.io.File构造函数。然后使用toPath方法来获取它。

相关问题