图片上传在项目中是经常用到的,做一个小的demo方便以后自己复习
这里用springboot的项目项目进行演示
目录结构
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、添加html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>文件上传入门案例</h1>
<form action="http://localhost:8091/file" method="post"
enctype="multipart/form-data">
文件名称:<input name="fileImage" type="file"/><br>
<input type="submit" value="提交"/>
</form>
</body>
3、编辑首页跳转的controller
package com.study.fileupload.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
4、文件跳转的url
package com.study.fileupload.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@RestController
public class FileController {
// http://localhost:8091/file
@RequestMapping("/file")
public String fileUpload(MultipartFile fileImage) throws IOException {
System.out.println(fileImage.getOriginalFilename());
final String imagePathRoot = "E:\\图片\\test-image\\";
File file = new File(imagePathRoot);
if (!file.exists()) {
file.mkdirs();
}
String fileName = fileImage.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf("."));
String uuid = UUID.randomUUID().toString().replace("-", "");
String imageFilePath = imagePathRoot + uuid + fileType;
fileImage.transferTo(new File(imageFilePath));
return "upload ok";
}
}
5、测试代码效果
5.1、http://localhost:8091/
5.2、选择一个本地图片
5.3、然后提交
5.4、查看文件是否上传成功
只是简答的演示,实际根据自己的业务场景怎加逻辑判断。