Reproduced in: https: //blog.csdn.net/weixin_44619613/article/details/108894101
Author: https: //blog.csdn.net/weixin_44619613
upload pictures in the project are often used to do a little demo convenience Review by yourself later
Here is a demonstration with the springboot project
Directory Structure
1. Add dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
1234
2. Add 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>
1234567891011121314151617
3. Edit the controller that jumps to the homepage
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";
}
}
1234567891011121314
4. The url of the file redirection
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";
}
}
12345678910111213141516171819202122232425262728293031323334
5. Test code effect
5.1、http://localhost:8091/
5.2. Choose a local picture
5.3, then submit
5.4. Check whether the file is uploaded successfully
It's just a short-answer demonstration, how to make logical judgments based on your own business scenarios.