gpt4 book ai didi

java - 从剩余参数创建目录

转载 作者:行者123 更新时间:2023-12-02 09:36:35 28 4
gpt4 key购买 nike

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

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));
}

但我得到了异常(exception):

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转换为字符串吗?

最佳答案

我认为抛出异常是因为目录 /opt/13 不存在。 Files.write 将创建文件,但没有父目录。以下是 Files.write 文档的一部分:

The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0.

替换以下行

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);

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 path
Files.write(newFile.toPath(), bytes);

关于java - 从剩余参数创建目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57459931/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com