Java-使用MultipartFile实现图片/文件上传
示例:
选择图片/文件
上传成功
前端代码:
<div class="form-item flexc">
<span class="form-item-name">请上传商品图片</span>
<div class="form-item-list flex">
<div class="form-case-itemupload ">
<input id="foodImgUrl" onchange="changeImg('foodImgUrl','food_img','uploadImgName')" type="file" name="" class="serve-type-btn1">
<img id="food_img" class="uploadimg" src="" alt="">
<!-- <i class="serve-type-img3"></i> -->
<i id="uploadImgName" class="serve-type-text3 c9">上传图片<br></i>
</div>
</div>
</div>
<div class="form-item flexc">
<span class="form-item-name">请上传商品相关资质资料</span>
<div class="form-item-list flex">
<div class="form-case-itemupload ">
<input id="qualImgUrl" onchange="changeImg('qualImgUrl','food_file','uploadTextName')" type="file" name="" class="serve-type-btn1">
<img id="food_file" class="uploadimg" src="" alt="">
<!-- <i class="serve-type-img3"></i> -->
<i id="uploadTextName" class="serve-type-text3 c9">上传凭证<br></i>
</div>
</div>
</div>
<div class="form-item ct">
<button onclick="addFood()" class="form-btn">确定</button>
</div>
function changeImg(inputEl,imgEl,nameEl){
var food_img_file = $("#"+inputEl)[0].files[0];
var imgUrl = getImgFileURL(food_img_file);
var fileName = food_img_file.name;
$("#"+imgEl).attr("src",imgUrl);
$("#"+nameEl).html(fileName);
}
//获取图片文件的路径
function getImgFileURL(file) {
var url = null ;
if (window.createObjectURL!=undefined) { // basic
url = window.createObjectURL(file) ;
} else if (window.URL!=undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file) ;
} else if (window.webkitURL!=undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file) ;
}
return url ;
}
function addFood(){
var foodImgFile = $('#foodImgUrl')[0].files[0];
uploadFile(foodImgFile);
var foodTextFile = $('#qualImgUrl')[0].files[0];
uploadFile(foodTextFile);
}
function uploadFile(file){
var formData = new FormData();
formData.append("file_data", file);
formData.append("type", "1");
$.ajax({
url: url,
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false,
success: function (data) {
},
error: function (err) {
}
});
}
Java后台:
@PostMapping("/upload")
@ResponseBody
public Map<String, Object> upload(@RequestParam("file_data") MultipartFile file_data, @RequestParam("type") String type) {
Map<String, Object> map = new HashMap<>();
if (file_data.isEmpty()) {
map.put("code", "ok");
}
// 获取文件名
String fileName = file_data.getOriginalFilename();
System.out.println("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("上传的后缀名为:" + suffixName);
// 文件上传后的路径
String filePath = "d:/upload/";
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file_data.transferTo(dest);
map.put("code", "ok");
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
有兴趣的朋友可以加我的qq群交流学习,群里有更多源码,学习资料
QQ群:741909960