前后端分离实现上传图片的功能
思路
- 前端上传图片和分类名称,保存图片文件,将数据追加到formData传给后端,回调清空。
- 后端对图片和分类名分开进行处理。分类名进行普通的增加。图片需要借助工具类转化成统一格式,再构造出“id+.jpg”的格式上传到文件夹中。
前端
<div class="panel panel-warning addDiv">
<div class="panel-heading">新增分类</div>
<div class="panel-body">
<table class="addTable">
<tr>
<td>分类名称</td>
<td><input @keyup.enter="add" v-model.trim="bean.name" type="text" class="form-control"></td>
</tr>
<tr>
<td>分类图片</td>
<td>
<input id="categoryPic" accept="image/*" type="file" name="image" @change="getFile($event)" />
</td>
</tr>
<tr class="submitTR">
<td colspan="2" align="center">
<a href="#nowhere" @click="add" class="btn btn-success">提交</a>
</td>
</tr>
</table>
</div>
</div>
bean 用来存放分类信息,file 用来表示上传的文件。
bean: { id: 0, name: ''},
file: null
getFile: function (event) {
this.file = event.target.files[0];
},
add: function () {
if(!checkEmpty(this.bean.name, "分类名称"))
return;
if(!checkEmpty(this.file, "分类图片"))
return;
var url = this.uri;
//axios.js 上传文件要用 formData 这种方式
var formData = new FormData();
formData.append("image", this.file);
formData.append("name", this.bean.name);
axios.post(url,formData).then(function(response){
vue.list(0);
vue.bean = { id: 0, name: '', hp: '0'};
$("#categoryPic").val('');
vue.file = null;
});
},
后端
controller
@PostMapping("/categories")
public Object add(Category bean, MultipartFile image, HttpServletRequest request) throws Exception {
categoryService.add(bean);
saveOrUpdateImageFile(bean, image, request);
return bean;
}
public void saveOrUpdateImageFile(Category bean, MultipartFile image, HttpServletRequest request)
throws IOException {
File imageFolder= new File(request.getServletContext().getRealPath("img/category"));
File file = new File(imageFolder,bean.getId()+".jpg");
if(!file.getParentFile().exists())
file.getParentFile().mkdirs();
image.transferTo(file);
BufferedImage img = ImageUtil.change2jpg(file);
ImageIO.write(img, "jpg", file);
}
service
public void add(Category bean) {
categoryDAO.save(bean);
}
工具类
- change2jpg 确保图片文件的二进制格式是jpg
- resizeImage用于改变图片大小
public class ImageUtil {
public static BufferedImage change2jpg(File f) {
try {
Image i = Toolkit.getDefaultToolkit().createImage(f.getAbsolutePath());
PixelGrabber pg = new PixelGrabber(i, 0, 0, -1, -1, true);
pg.grabPixels();
int width = pg.getWidth(), height = pg.getHeight();
final int[] RGB_MASKS = { 0xFF0000, 0xFF00, 0xFF };
final ColorModel RGB_OPAQUE = new DirectColorModel(32, RGB_MASKS[0], RGB_MASKS[1], RGB_MASKS[2]);
DataBuffer buffer = new DataBufferInt((int[]) pg.getPixels(), pg.getWidth() * pg.getHeight());
WritableRaster raster = Raster.createPackedRaster(buffer, width, height, width, RGB_MASKS, null);
BufferedImage img = new BufferedImage(RGB_OPAQUE, raster, false, null);
return img;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static void resizeImage(File srcFile, int width,int height, File destFile) {
try {
if(!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
Image i = ImageIO.read(srcFile);
i = resizeImage(i, width, height);
ImageIO.write((RenderedImage) i, "jpg", destFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Image resizeImage(Image srcImage, int width, int height) {
try {
BufferedImage buffImg = null;
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
buffImg.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
return buffImg;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}