首页 > 解决方案 > 文件未保存到目录中

问题描述

我想使用此代码将文件上传到 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

标签: javaspringfile

解决方案


而不是使用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);

与其对+一堆Strings 使用运算符来创建新文件的路径,不如使用java.io.File构造函数。然后使用toPath方法来获取它。


推荐阅读