6.springboot实现文件上传
2020-03-20 本文已影响0人
0f701952a44b
1.html代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>springboot html test</title>
</head>
<body>
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="imgname">
<button type="submit">提交</button>
</form>
</body>
</html>
2.返回内容bean
public class JSONData implements Serializable{
private static final long serialVersionUID = 1L;
private int code;
private String message;
private Object data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public JSONData(int code, Object data) {
super();
this.code = code;
this.data = data;
}
public JSONData(int code, String message, Object data) {
super();
this.code = code;
this.message = message;
this.data = data;
}
}
3.Controller
@RestController
public class FileUploadController {
@RequestMapping("/upload")
public Object uploadFile(@RequestParam("imgname")MultipartFile file) {
if(file.isEmpty()) {
return new JSONData(0, "上传文件不能为空", null);
}
if(file.getSize()>1024*1024) {
return new JSONData(0, "上传文件不能大于1M", null);
}
String filename = file.getOriginalFilename();
System.out.println("文件名:"+filename);
String suffixname = filename.substring(filename.lastIndexOf("."));
System.out.println("后缀:"+suffixname);
System.out.println("姓名:"+username);
filename = UUID.randomUUID()+suffixname;
File uploadfile = new File("E:\\springbootstudy\\demo1\\src\\main\\resources\\static\\img\\"+filename);
try {
file.transferTo(uploadfile);
return new JSONData(1, uploadfile);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
return new JSONData(0, "文件上传失败",null);
}
}