java 上传文件

package com.cosw.szt.manage.web.controller.ticketmanage;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.springframework.web.multipart.MultipartFile;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class SavePic {
//保存图片操作。
public static String savePic(MultipartFile multipartFile, String filePath) throws Exception {
//File file = new File(picName);
//String name = picName.substring(picName.lastIndexOf("."));

// 新文件名
int random = (int) (Math.random() * 10000);
String fileName = System.currentTimeMillis() + random + multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."));

//if (name.equals(".jpg") || name.equals(".gif")) {
//InputStream input = new FileInputStream(file);
//BufferedImage bi = ImageIO.read(input);
//if (bi != null) {
if (htmlUpload(multipartFile.getInputStream(), filePath, "BIG_" + fileName)) {
System.out.println("上传成功!");
uploadJPGfile(multipartFile.getInputStream(), filePath, "SMALL_" + fileName);
} else {
System.out.println("上传失败!");
}
//} else {
//System.out.println("你选择的图片错误或者该图片已经损坏!"); // 给出提示
//}
return fileName;
}


//正常大小
private static boolean htmlUpload(InputStream inputStream,String filePath, String fileName) {
        try {
            InputStream input = inputStream;
          
            byte[] buff = new byte[4096];
            FileOutputStream output = new FileOutputStream(filePath + fileName);
            int bytecount = 1;
            while ((bytecount = input.read(buff, 0, 4096)) != -1) {
                output.write(buff, 0, bytecount);
            }
            output.flush();
            output.close();
            return true;
        } catch (Exception e) {
            return false;
        }
}
//小图片
public static boolean uploadJPGfile(InputStream inputStream,String filePath, String fileName) throws Exception {
   
int new_w = 150;
int new_h = 100;
BufferedImage tag = new BufferedImage(new_w, new_h,
BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(ImageIO.read(inputStream), 0, 0, new_w, new_h, null);
FileOutputStream out = new FileOutputStream(filePath + fileName);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
return true;
}
}


在控制器中的处理
public String save(@RequestParam("picNameFile") MultipartFile picNameFile){
if(!picNameFile.isEmpty()){
// 上传文件存放的路径
String filePath = PropertyUtil.getProperty("upload.image.root-path")
     +System.getProperty("file.separator")+"commodity"+System.getProperty("file.separator");
String fileName = SavePic.savePic(picNameFile,filePath);
//保存图片地址。暂时路径+文件名
ticket.setPicName(filePath + "BIG_" + fileName);
ticket.setImgName(filePath + "SMALL_" + fileName);
}

}



猜你喜欢

转载自pinganhongguo.iteye.com/blog/1047352