用idea进行上传图片(文件)

在进行图片上传中 Action的添加

private BookService bs;
private Book book;
private fiel file1;
private String file1FileName;(错误原因:自己没有按照前面的变量名来取,而是自己命名了一个file2
导致出错,报空指针异常。固定写法file1FileName)
生成get/set方法
public String insert(){
 	String newFIle = UUID.randowUUID.toString() + file1FileName.substring(file1FileName.lastIndexOf("."));
 	book.setOldName(file1FileName);
 	book.setNewName(newFile);
 	bs.insert(book);

在页面中写成

<input name="file1" type="file" ...>

}

首先,你需要在你的项目中添加spring-boot-starter-web 和 spring-boot-starter-thymeleaf依赖。然后在你的控制器中添加如下代码: ```java @Controller public class ImageController { @GetMapping("/upload") public String uploadForm(Model model) { return "uploadForm"; } @PostMapping("/upload") public String uploadSubmit(@RequestParam("file") MultipartFile file, Model model) { // 处理文件上传逻辑 return "uploadResult"; } } ``` 在这个控制器中,我们定义了两个方法:`uploadForm` 和 `uploadSubmit`。`uploadForm` 方法返回一个视图,用于显示上传表单。`uploadSubmit` 方法处理文件上传的逻辑,并返回一个视图,用于显示上传结果。 接下来,我们需要创建上传表单的视图。在resources/templates目录下创建一个uploadForm.html文件,添加如下代码: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Upload Form</title> </head> <body> <h1>Upload Form</h1> <form th:action="@{/upload}" method="post" enctype="multipart/form-data"> <input type="file" name="file"/><br/><br/> <input type="submit" value="Upload"/> </form> </body> </html> ``` 在这个模板中,我们使用了Thymeleaf模板引擎。`th:action="@{/upload}"`指定了表单提交的地址为`/upload`,`enctype="multipart/form-data"`指定了表单的编码类型为多部分表单数据格式,以支持文件上传。 最后,我们需要创建一个上传结果的视图。在resources/templates目录下创建一个uploadResult.html文件,添加如下代码: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Upload Result</title> </head> <body> <h1>Upload Result</h1> <p th:text="${message}"></p> </body> </html> ``` 在这个模板中,我们使用了Thymeleaf模板引擎。`th:text="${message}"`指定了显示上传结果的消息。 现在我们可以在浏览器中访问/upload路径,上传照片并查看上传结果了。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值