这个servlet是接收手机端的图片,然后对图片处理,达到质量小(图片大小),不变形保持原来上传的原样!上传的图片是Jpg格式的,还要把图片处理为Png格式,图片名的后缀改为png之外,前缀不变!本人现在用的是这个方法:但是app端上传成功后,服务器这边打不到图片,
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb factory.setRepository(tempPathFile);// 设置缓冲区目录 // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB List<FileItem> items = upload.parseRequest(request);// 得到全部的文件 Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fileName = fi.getName(); if (fileName != null) { File fullFile = new File(fi.getName()); File savedFile = new File(uploadPath, fullFile.getName()); InputStream is = new FileInputStream(fileName); BufferedImage buff = ImageIO.read(is); BufferedImage bi = ImageIO.read(fullFile); Image mImage = bi.getScaledInstance(buff.getWidth(),buff.getHeight(), Image.SCALE_DEFAULT); BufferedImage tag = new BufferedImage(buff.getWidth(), buff.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(mImage, 0, 0, null); g.dispose(); is.close(); ImageIO.write(tag, "png", new FileOutputStream(savedFile)); // fi.write(savedFile); // FileOutputStream out = new FileOutputStream(outputDir + outputFileName); // // JPEGImageEncoder可适用于其他图片类型的转换 // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // encoder.encode(tag); // out.close(); } } System.out.print("upload succeed"); } catch (Exception e) { System.out.println(e.getMessage()); // 可以跳转出错页面 e.printStackTrace(); } }
解决方案
40
if语句修改为
File savedFile = new File(uploadPath, fi.getName()); InputStream is = fi.getInputStream(); BufferedImage buff = ImageIO.read(is); Image mImage = buff.getScaledInstance(buff.getWidth(),buff.getHeight(), Image.SCALE_DEFAULT);