工具类:imgutils
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class ImgUtils {
/**
* 上传判定
* @param imagePath 图片链接
* @param imageName 图片名称
* @param input 输出流
* @return
*/
public static boolean uploadImage(String imagePath, String imageName, InputStream input) {
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;
File realFile = new File(imagePath);
if (!realFile.exists())
realFile.mkdirs();
try {
// 新建文件输入流并对它进行缓冲
inBuff = new BufferedInputStream(input);
// 新建文件输出流并对它进行缓冲
outBuff = new BufferedOutputStream(new FileOutputStream(imagePath + imageName));
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
} catch (FileNotFoundException a) {
a.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
try {
if (inBuff != null)
inBuff.close();
if (outBuff != null)
outBuff.close();
} catch (IOException c) {
c.printStackTrace();
}
}
return true;
}
}
应用业务层
public PictureResult uploadPicture(MultipartFile uploadFile) {
//判断上传图片是否为空
if (null == uploadFile || uploadFile.isEmpty()) {
return PictureResult.error("上传图片为空");
}
//取文件扩展名
String originalFilename = uploadFile.getOriginalFilename();
String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
//生成新文件名(可以使用uuid生成新文件名、可以是时间+随机数生成文件名)
//UUID.randomUUID()
String imageName = genImageName();
//文件在服务器的存放路径,应该使用日期分隔的目录结构
//DateTime dateTime = new DateTime();
//String filePath = dateTime.toString("/yyyy/MM/dd");
try {
ImgUtils.uploadImage(IMAGE_BASE_URL+"/uploadImg/", imageName + ext, uploadFile.getInputStream());
} catch (Exception e) {
e.printStackTrace();
return PictureResult.error(ExceptionUtil.getStackTrace(e));
}
//返回结果,生成一个可以访问到图片的url返回
return PictureResult.ok(IMAGE_SHOW_URL+"/uploadImg/" + imageName + ext);
}
/**
* 图片名生成
*/
public static String genImageName() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上三位随机数
Random random = new Random();
int end3 = random.nextInt(999);
//如果不足三位前面补0
String str = millis + String.format("%03d", end3);
return str;
}
返回数据处理实体
public class PictureResult {
private int error;
private String url;
private String message;
private PictureResult(int error, String url, String message) {
this.error = error;
this.url = url;
this.message = message;
}
// 成功时调用的方法
public static PictureResult ok(String url) {
return new PictureResult(0, url, null);
}
// 失败时调用的方法
public static PictureResult error(String message) {
return new PictureResult(1, null, message);
}
。。。。
}