springboot代码
@RequestMapping("/uploadImgFile")public Map<String,String> uploadImgFile(MultipartFile file,HttpServletRequest request) {Map<String,String> map = new HashMap<String,String>();try{String fileName = file.getOriginalFilename();String type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;if ("JPG".equals(type.toUpperCase())||"JPEG".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())) {//获取服务器名String hostAddress = InetAddress.getLocalHost().getHostAddress();// 自定义的文件名称String trueFileName = new Date().getTime()+"."+type;// 设置存放文件的路径String path = ResourceUtils.getURL("classpath:").getPath()+"static/img/" + trueFileName;File dest = new File(path);//判断文件父目录是否存在if (!dest.getParentFile().exists()) {dest.getParentFile().mkdir();}file.transferTo(dest);map.put("1","文件上传成功");map.put("imgUrl","http://"+hostAddress+":"+port+ "/img/" + trueFileName);}else{map.put("0","图片格式不对");}}catch (Exception e){map.put("0","文件上传失败");}return map;}
vue代码
按钮
<button class="right-update">上传图片<input type="file" @change="selectImgChange" ref="imgfile"></button>
样式
.right-updateheight: 2rem;top:0.5rem;left:6rem;width:10rem;border:0.05rem solid #CCC;border-radius: 0.4rem;text-align: center;font-size: 1rem;font-weight:bold;inputwidth:100%;height: 100%;position:absolute;left:0;opacity:0;cursor: pointer;
事件
methods: {selectImgChange:function(){let file = this.$refs.imgfile.files[0];var formData = new FormData();formData.append("file",file);axios({method:'post',url:this.dataUrl+"/uploadImgFile",data:formData,headers: {'Content-Type': 'multipart/form-data'}}).then(function(response){console.log(response.data)})}}