vue上传图片至项目resources文件夹,将路径返回至前端,并将路径保存在数据库;
前端代码:
<el-form-item label="商品图片:" :sm="3" prop="pic">
<el-col :sm="16">
<el-upload class="upload-demo" drag multiple list-type="picture"
accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF"
action="/api/goods/uploadPhoto" name="pic"
:on-success="handleUploadPhotoSuccess" :on-remove="handlePhotoRemove">
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传jpg/png文件</div>
</el-upload>
</el-col>
</el-form-item>
后端代码:
@RequestMapping("/uploadPhoto")
@ResponseBody
public Result uploadPhoto(@RequestParam("pic") MultipartFile pic,HttpServletResponse response) throws IOException {
System.out.println(pic);
/*
* 编码为字符串*/
String s = Base64Utils.encodeToString(pic.getBytes());
System.out.println("s:"+s);
/* *
*2.解码成字节数组
*/
Base64.Decoder decoder = Base64.getDecoder();
byte[] bytes = decoder.decode(s);
/*
* 3.字节流转文件
*/
String d = System.getProperty("user.dir");
File fileMkdir = new File(d+"\\goods-sys\\src\\main\\resources\\static\\img");
if (!fileMkdir.exists()){
fileMkdir.mkdir();
}
String pathName = fileMkdir.getPath() + "\\" + pic.getOriginalFilename();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(pathName);
fos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Result result= new Result(CodeMsg.SUCESS);
result.setData("img\\"+ pic.getOriginalFilename());
return result;
}
@RequestMapping("/add")
@ResponseBody
public Result addGoods(PmsProduct goods) {
System.out.println("====" + goods.getName() + goods.getPrice() + "==description=" + goods.getDescription());
System.out.println("==pic==" + goods.getPic());
goods.setProductSn(OrderUtil.generateTransferNo());
goods.setDescription(goods.getDescription().substring(3,goods.getDescription().length()-4));
System.out.println("==description=" + goods.getDescription());
goods.setProduceId(1001);
goods.setPic(goods.getPic());//保存图片路径
int flag = goodsService.addGoods(goods);
System.out.println("==flag==" + flag);
if (flag > 0) {
return new Result(CodeMsg.SUCESS);
}
return new Result(CodeMsg.REQUEST_ILLEGAL);
}