(1)编写接收数据类
@Data
public class Result {
private int errno;
private String[] data;
}
(2)编写控制器,接收上传图片
@RequestMapping("/upload")
@ResponseBody
public Result upload(HttpServletRequest request, MultipartFile file) throws IOException {
String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/upload";
File dir = new File(realPath);
if (!dir.exists()){
dir.mkdirs();
}
String filename = file.getOriginalFilename();
filename = UUID.randomUUID()+filename;
File newFile = new File(dir, filename);
file.transferTo(newFile);
Result Result = new Result();
Result.setErrno(0);
String[] data = {"/upload/"+filename};
Result.setData(data);
return Result;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
(3)在yml文件中配置允许传输文件的大小
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
(4)编写前端页面
②修改页面
<div class="col-md-8 data" style="height: 110px">
<form id="uploadPImage" enctype="multipart/form-data">
<input type="file" name="file" id="pImageFile">
form>
div>
<script>
$(function (){
$("#pImageFile").change(function (){
$("#uploadPImage").ajaxSubmit({
url:"/backstage/product/upload",
type: "post",
success:function (result){
$("#pImage").attr("src",result.data[0]);
$("#hiddenPImage").val(result.data[0]);
}
})
})
})
script>
<div class="col-md-2 data" style="height: 110px">
<img height="100" th:src="@{/backstage/img/no-img.png}" id="pImage">
div>
<form th:action="@{/backstage/product/add}" method="post">
<input type="hidden" name="pImage" id="hiddenPImage">
form>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29