记录一下项目中遇到的上传问题,base64上传和MultipartFile上传具体实现!
<div class="form-group">
<label class="col-sm-3 control-label"> <em style="color: red;font-style: normal;">*</em> 门店图片:</label>
<div class="col-sm-8">
<div class="mendian">+</div>
<input type="file" id="fileUp"style="display:none;">
</div>
</div>
<butten type="submit" id="submit"></butten>
var tx_base64 = "" ; //图片路径
$("submin").on("click",function(){
upload();
});
function upload(){
/* 此处获取上传图片的base64码*/
var a = $(".mendian").css("background");
a = a.substring(a.indexOf("base64,") + 7, a.length - '") repeat scroll 50% 50% / cover padding-box border-box'.length);
var storeData = new Object();
storeData.imgMechanics = a;
//还有其他实体此处忽略
$.ajax({
cache: true,
type: "POST",
url: "/save",
data: JSON.stringify(storeData),//JSON序列化
contentType: "application/json",//比较关键
// 只做上传测试可以忽略返回操作部分
error: function (request) {
parent.layer.alert("Connection error");
},
success: function (data) {
if (data.code == 0) {
parent.layer.msg("操作成功");
parent.reLoad();
var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
parent.layer.close(index);
} else {
parent.layer.alert(data.msg)
}
}
});
}
//门店图片上传图片选择及回显
$(".mendian").click(function () {
$("#fileUp").click()
});
$('#fileUp').on('change',function(e){
var b=$("#fileUp").val();
$("#fbgimg").val(new Date().getTime()+ "_" +b.substr(b.lastIndexOf("\\")+1));
var file = e.target.files || e.dataTransfer.files;
if (file) {
var reader = new FileReader();
reader.onload = function () {
$('.mendian').html("");
$('.mendian').css({"background":" url(" + this.result + ") center center","background-size":"cover"});
tx_base64 = this.result;
}
reader.readAsDataURL(file[0]);
}
});
//R 为项目要求另写的返回要求,在本次base64上传中可以忽略,或根据自己替换
@ResponseBody
@PostMapping("/save")
//由于ajax传值JSON序列化了,所以必须使用 @RequestBody 注解,否则接收不到
public R save( @RequestBody StoreDataDO storeData ) {
String path = storeData.getFbgimg();//图片路径实体,方便数据存储用,本例可以忽略
String sqlpath = "../img/store/"+path; //数据库保存路径
String savePath ="E:\\"; //上传文件保存路径
storeData.setFbgimg(sqlpath);
//开始处理上传
File dest;
dest = new File(savePath+path);
//判断父目录是否存在,不存在则创建
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
//使用工具类 提供的方法 generateImage(String imgStr, String path) 上传图片并保存
if(generateImage(storeData.getImgMechanics(),savePath+path) && storeDataService.save(storeData)>0 ) {
return R.ok();
}
return R.error();
}
public class Base64ToPhoto {
public static boolean generateImage(String imgStr, String path) {
if (imgStr == null) {
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
// 解密
byte[] b = decoder.decodeBuffer(imgStr);
// 处理数据
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}
<div class="form-group">
<label class="col-sm-3 control-label"> <em style="color: red;font-style: normal;">*</em> 门店图片:</label>
<div class="col-sm-8">
<div class="mendian">+</div>
<input type="file" id="fileUp"style="display:none;">
</div>
</div>
<butten type="submit" id="submit"></butten>
$("submin").on("click",function(){
upload();
});
function upload(){
var formData = new FormData();
formData.append("file", $("#fileUp")[0].files[0]);
$.ajax({
cache: true,
type: "POST",
url: "/save",
data: formData ,
cache: false,
contentType: false,
processData: false,
success: function (data) {
}
});
}
//门店图片上传图片选择及回显
$(".mendian").click(function () {
$("#fileUp").click()
});
$('#fileUp').on('change',function(e){
var b=$("#fileUp").val();
$("#fbgimg").val(new Date().getTime()+ "_" +b.substr(b.lastIndexOf("\\")+1));
var file = e.target.files || e.dataTransfer.files;
if (file) {
var reader = new FileReader();
reader.onload = function () {
$('.mendian').html("");
$('.mendian').css({"background":" url(" + this.result + ") center center","background-size":"cover"});
tx_base64 = this.result;
}
reader.readAsDataURL(file[0]);
}
});
//@RequestParam 中的 value 值需要和js [ formData.append("file", $("#fileUp")[0].files[0]) ]中append 第一个参数 "file" 一致
@RequestMapping("/save")
public Object fileUpload(@RequestParam(value = "file", required = false) MultipartFile file){
if (file.isEmpty()) {
return "上传文件不可为空";
}
String newfileName = file.getOriginalFilename();
newfileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + newfileName;//(加个时间戳,尽量避免文件名称重复)
String path = "E:\\" + newfileName;
File dest = new File(path);
//判断文件是否已经存在
if (dest.exists()) {
return "文件已经存在";
}
//判断文件父目录是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest); //保存文件
} catch (IOException e) {
return "上传失败";
}
return dest ;
}
本次都只写了 base64 和 MultipartFile 的单文件上传,项目中遇到,便记录了下来,常用的还是 多文件上传+数据一起提交