前端Ajax上传文件并发送请求
js
function uplodeFile() {
var file=$('#Agreement_file')[0].files[0];
console.log(file);
var form = new FormData();
form.append('img',file);
$.ajax({
type: 'POST',
url: '/hotel/uplodeImg',
data: form,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
var imageURL=data.data;
$('#pImg').attr('src',imageURL);
}
})
}
$(document).ready(function(data){
$("#btn_choose_file").click(function(){
$("#Agreement_file").trigger("click");
});
});
jsp
<div class="box-tools text-center">
<img id="pImg" class="uplodeimg" src="" height="180px">
<input id="Agreement_file" type="file" style="display:none" onchange="uplodeFile();" />
<button id="btn_choose_file" type="button" class="btn bg-uplode">点击上传</button>
</div>
后端SpringBoot文件静态映射,存储并返回文件路径
controller
@RequestMapping("/uplodeImg")
public Object uplodeImg(MultipartFile img){
String uplodeImg = iHotelService.uplodeImg(img);
return Result.init(200, "success", uplodeImg);
}
service
@Value("${file.rootPath}")
String ROOT_PATH;
@Value("${file.sonPath}")
String SON_PATH;
@Value("${file.localPath}")
String localPath;
@Override
public String uplodeImg(MultipartFile file) {
if (file.isEmpty()) {
throw new NullPointerException("文件为空");
}
String filePath = ROOT_PATH + SON_PATH;
String suffix = file.getOriginalFilename();
String prefix = suffix.substring(suffix.lastIndexOf(".")+1);
String fileName = UUID.randomUUID()+ "." + prefix;
System.out.println("fileName: "+fileName);
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
String filePathNew = localPath + fileName;
System.out.println(filePathNew);
return filePathNew;
} catch (Exception e) {
return dest.toString();
}
}
application.yml
file:
rootPath: "E:"
sonPath: "/takeout/img/"
localPath: "http://localhost:8080/file/img/
配置静态文件映射
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
String path = "E:\\takeout\\";
registry.addResourceHandler("/file/**").addResourceLocations("file:" + path);
}
}