前台代码:
<form id="userForm" method="post" enctype="multipart/form-data"> <div> <label class="my_input_title">图片1:</label> <input type="file" name="file" class="" id="" value="" placeholder="请选择图片1"/> </div> <div> <label class="my_input_title">图片2:</label> <input type="file" name="file" class="" id="" value="" placeholder="请选择图片2"/> </div> </form>
后台工具类代码:
public static void photoupload(xxx x, @RequestParam("file") CommonsMultipartFile files[],ResultJson rj){ /******************************图片上传start**********************************/ InputStream input = null; ByteArrayOutputStream bos = null; // 获得项目的路径 //ServletContext sc = request.getSession().getServletContext(); // 上传的文件要保存到的路径 String path = ("E:/x/"+x.getxRealname()+"/"); File file = new File(path); if (!file.exists()) file.mkdirs(); for (int i = 0; i < files.length; i++) { try { if (!files[i].isEmpty()) { // 获得原始文件名 String fileName = files[i].getOriginalFilename(); System.out.println(i+"原始文件名:" + fileName); bos = new ByteArrayOutputStream(); input = files[i].getInputStream(); Image image = ImageIO.read(input); // 图片压缩 BufferedImage tag = new BufferedImage(239,127, BufferedImage.TYPE_INT_RGB); tag.getGraphics().drawImage(image.getScaledInstance(239,127,Image.SCALE_SMOOTH),0,0,null); if (files[i].getOriginalFilename().endsWith(".jpg")) { ImageIO.write(tag, "jpg", bos); } else if (files[i].getOriginalFilename().endsWith(".png")) { ImageIO.write(tag, "png", bos); } else { rj.setMsg("上传图片格式错误"); rj.setObj(""); rj.setSuccess(false); } byte[] bytes = bos.toByteArray(); // 新文件名 String newFileName = UUID.randomUUID() + fileName; FileOutputStream fos = new FileOutputStream(path + newFileName); fos.write(bytes); input.close(); fos.close(); System.out.println("上传图片到:" + path + newFileName); if(i==0){ x.setXPath(path + newFileName); }else{ x.setYPath(path + newFileName); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /*******************************图片上传end**************************************/ }
逻辑如上,自己可修改相关参数实现,如上即可实现图片压缩上传!