从 rest 参数创建目录

我想在一个主根目录下创建目录。我试过这段代码:


private static String UPLOADED_FOLDER = "/opt/";


@PostMapping

public ResponseEntity<StringResponseDTO> uploadData(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes, @RequestParam("id") Integer merchant_id) throws Exception {    

    InputStream inputStream = file.getInputStream();

    String originalName = file.getOriginalFilename();

    String name = file.getName();

    String contentType = file.getContentType();

    long size = file.getSize();

    LOG.info("name: " + name);

    LOG.info("contentType: " + contentType);

    LOG.info("size: " + size);


    try {

        byte[] bytes = file.getBytes();           

        File newFile = new File(UPLOADED_FOLDER + merchant_id, file.getOriginalFilename());

        LOG.info("New file location: " + newFile.getAbsolutePath()); //Log the path

        Files.write(newFile.toPath(), bytes);


    } catch (IOException e) {

        e.printStackTrace();

    }


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

}

但我得到例外:


2019-08-12 09:53:30,748 INFO  [stdout] (default task-79) 09:53:30.747 [default task-79] INFO  o.d.a.b.restapi.MerchantController - New file location: /opt/13/Screenshot 2019-08-01 at 14.58.59.png

2019-08-12 09:53:30,749 ERROR [stderr] (default task-79) java.nio.file.NoSuchFileException: /opt/13/Screenshot 2019-08-01 at 14.58.59.png

2019-08-12 09:53:30,750 ERROR [stderr] (default task-79)    at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)

我需要将数字转换merchant_id成字符串吗?


小唯快跑啊
浏览 133回答 1
1回答

jeck猫

我认为抛出异常是因为目录/opt/13不存在。Files.write将创建文件,但没有父目录。这是Files.write文档的一部分:options 参数指定文件的创建或打开方式。如果不存在任何选项,则此方法的工作方式就像存在 CREATE、TRUNCATE_EXISTING 和 WRITE 选项一样。换句话说,它打开文件进行写入,如果文件不存在则创建文件,或者最初将现有的常规文件截断为 0 大小。替换以下行File newFile = new File(UPLOADED_FOLDER + merchant_id, file.getOriginalFilename());LOG.info("New file location: " + newFile.getAbsolutePath()); //Log the pathFiles.write(newFile.toPath(), bytes);和File directory = new File(UPLOADED_FOLDER, merchant_id.toString());directory.mkdirs();File newFile = new File(directory, file.getOriginalFilename());LOG.info("New file location: " + newFile.getAbsolutePath()); //Log the pathFiles.write(newFile.toPath(), bytes);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java