gpt4 book ai didi

java - 如何在 spring mvc 中使用 url 路径中的 id 创建文件夹?我已经创建了文件夹,但我想使用 upload.html 中的 id 创建文件夹?

转载 作者:太空宇宙 更新时间:2023-11-04 11:36:26 26 4
gpt4 key购买 nike

我是新的 Spring Boot 。我的任务是创建文件夹。

这是 Controller 代码。我已经创建了文件夹但想使用 id 创建?并添加多个文件并删除它们。

  @Controller
public class UploadController {

//Save the uploaded file to this folder
private static String UPLOADED_FOLDER = "E://temp//";

@GetMapping("/")
public String index() {
return "upload";
}

@PostMapping("/upload") // //new annotation since 4.3
public String singleFileUpload(@RequestParam("id") Long id,
@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {

if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}


try
{
Long userId;
byte[] bytes = file.getBytes();
String filename =file.getOriginalFilename();
int pos=filename.lastIndexOf(".");
System.out.println(pos);
if (pos>0)
{
filename=filename.substring(0, pos);
}
System.out.println(filename);
File folder=new File("E:\\temp\\"+filename+"\\");
System.out.println(folder);
folder.mkdirs();


Path path = Paths.get("E:\\temp\\"+filename+"\\"+ file.getOriginalFilename());
System.out.println(UPLOADED_FOLDER);
Files.write(path, bytes);




redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
}
catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}

这是我的 HTML 代码 upload.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>

<h1>Spring Boot file upload example</h1>

<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input typr="text" name="id" /><br>
<input type="submit" value="Submit" />
</form>

</body>
</html>

最佳答案

File file = new File("C:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}

上面的代码将为您创建目录。在路径中附加您的 id 将会使用您的“id ”创建目录。

关于java - 如何在 spring mvc 中使用 url 路径中的 id 创建文件夹?我已经创建了文件夹,但我想使用 upload.html 中的 id 创建文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43226333/

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