搞了一天多,遇到了很多问题,整理下来记录一下,好用的请点赞哦
前端代码html:
<button style="position:relative;" class="btn btn-primary" id="btn" name="btn">上传图片</button>
<input type="file" name="file" id="file" onchange="uploadImage(this);" style="opacity:0;width:100%;height:100%;position:absolute;top:0;left:0">
js提交:
function uploadImage(obj) {
console.log("obj="+obj)
var f = $(obj).val();
console.log("f="+f);
if(f == null ||f == undefined || f == ""){
return false;
}
if(!/\.(?:png|jpg|bmp|gif|PNG|JPG|BMP|GIF)$/.test(f)){
alert("类型必须是图片(.png|jpg|bmp|gif|PNG|JPG|BMP|GIF)");
$(obj).val("");
return false;
}
------------------------------------
单图上传
var formData = new FormData();
// debugger
console.log($(obj)[0].files[0])
formData.append("file",$("#file")[0].files[0]);
---------------------------------------
批量上传
var formData = new FormData(); // debugger console.log($(obj)[0].files[0]) var files = $("#file")[0].files; for(var i=0;i<files.length;i++){ formData.append("file",$("#file")[0].files[i]); }
----------------------------------
$.ajax({
type:"POST",
url : apiPath+"/admin/upload/uploadimg",
data : formData,
cache : false,
processData : false, //JQuery不处理发送数据
// contentType : 'multipart/form-data',//(如果这样,会导致contentType没有边界boundary,导致文件解析失败,后台报错Could not parse multipart servlet request;)
contentType : false,
success : function(result) {
if(result.code == "200") {
console.log(result.data);
alert("图片上传成功")
window.location.reload()
}
}
});
}
后台服务Controller:
package com.kankan.service.admin.upload; import com.kankan.core.entity.R; import com.kankan.module.sys.entity.SysQrCode; import com.kankan.module.sys.logic.SysQrCodeLogic; import com.kankan.module.system.entity.GlobalConfig; import com.kankan.module.system.logic.GlobalConfigLogic; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.*; @RestController @RequestMapping("/admin/upload/") @Api public class UploadImageController { /*@Value("${admin.images.uploadPath}") private String uploadPath;*/ @Resource SysQrCodeLogic sysQrCodeLogic; @Resource GlobalConfigLogic globalConfigLogic; @ApiOperation(value = "上传文件") @PostMapping("uploadimg") public R<Map> uploadImages1(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response){ GlobalConfig config = globalConfigLogic.getByGlobalKey("admin.images.uploadPath"); String uploadPath = config.getGlobalValue(); Map resultMap = new HashMap(); // uploadPath = "c:/java/project/images/"; String fileName = uploadFile(uploadPath,file); SysQrCode code = new SysQrCode(); code.setPath(fileName); code.setStatus("1"); code.setCtime(new Date()); code.setCtime(new Date()); sysQrCodeLogic.save(code); resultMap.put("path",fileName); return R.ok(resultMap); } private String uploadFile(String uploadPath,MultipartFile file){ InputStream inputStream = null; OutputStream os = null; String path = null; String fileName = new Date().getTime()+"_"+file.getOriginalFilename(); try{ byte[] bs = new byte[1024]; // 读取到的数据长度 int len; // 输出的文件流保存到本地文件 File tempFile = new File(uploadPath); if (!tempFile.exists()) { tempFile.mkdirs(); } inputStream = file.getInputStream(); path = tempFile.getPath() + File.separator + fileName; os = new FileOutputStream(path); // 开始读取 while ((len = inputStream.read(bs)) != -1) { os.write(bs, 0, len); } }catch (IOException e){ e.printStackTrace(); }finally { // 完毕,关闭所有链接 try { os.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return fileName; } @ApiOperation(value = "批量上传文件") @PostMapping("uploadimgs") public R<Map> uploadImages1(@RequestParam("file") MultipartFile[] files){ GlobalConfig config = globalConfigLogic.getByGlobalKey("admin.images.uploadPath"); String uploadPath = config.getGlobalValue(); // uploadPath = "c:/java/project/images/"; Map resultMap = new HashMap(); uploadPath = "c:/java/project/images/"; for(MultipartFile file:files){ String fileName = uploadFile(uploadPath,file); SysQrCode code = new SysQrCode(); code.setPath(fileName); code.setStatus("1"); code.setCtime(new Date()); code.setCtime(new Date()); sysQrCodeLogic.save(code); } resultMap.put("path",""); return R.ok(resultMap); } }