由于现在很多业务需要文件上传,而且前端上传的格式不同,有的是Base64格式,也可能是正常的图片格式,所以就把这些整理出来,方便以后用到。也方便大家。如果有什么不好之处,请大家麻烦给点意见。谢谢!!
基于maven 创建的文件上传。
所需要的 jar
commons-fileupload commons-fileupload 1.3.1
commons-httpclient commons-httpclient 3.1
net.coobird thumbnailator 0.4.8 //图片压缩所用
首先 方法要实现 ServletContextAware 类 重写 ServletContext
public class FileController implements ServletContextAware{
private ServletContext servletContext;
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
}
下面是上传正常图片格式的代码
@RequestMapping(value="fileUploadImg",method=RequestMethod.POST)
@ResponseBody
public JsonData fileUpload( @RequestParam("file") CommonsMultipartFile file){
JsonData data = new JsonData();
data.setResult(0);
try {
//文件上传保存的路径
String realPaths = Config.UPLOAD_BASE_DIR+"/"+DateUtil.stampToDate(System.currentTimeMillis(), "yyyy/MM/dd");
String abspath = servletContext.getRealPath(realPath);//获取绝对路径
File uploadDir = new File(abspath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
String fileName = randName() + file.getOriginalFilename();//设置文件名
File tagelFile = new File(abspath, fileName);
file.transferTo(tagelFile);
System.out.println(tagelFile.getPath());
data.setData(fileName); data.setResult(1);
} catch (Exception e) {
e.printStackTrace();
data.setErrMsg("图片服务器服务繁忙");
}
return data;
}
设置随机的文件名 防止出现重名
/** * 随机 * * @return */
@SuppressWarnings("static-access")
private static String randName() {
Calendar calendar = Calendar.getInstance();
StringBuffer sb = new StringBuffer();
sb.append(calendar.get(calendar.YEAR));
sb.append(calendar.get(calendar.MONTH) + 1);
sb.append(calendar.get(calendar.DATE));
sb.append(calendar.get(calendar.HOUR));
sb.append(calendar.get(calendar.MINUTE));
sb.append(calendar.get(calendar.SECOND));
Random random = new Random();
Integer n = random.nextInt(999999);
sb.append(n.toString());
return sb.toString();
}
前端上传的图片格式为base64的上传代码如下
@RequestMapping(value="base64File",method=RequestMethod.POST)
@ResponseBody
public JsonData base64File(@RequestBody String file){
MyLogUtils.getInstance().log("开始上传图片");
JsonData data = new JsonData();
data.setResult(1);
try {
file=file.replaceAll("\"", "");
String realPath = Config.UPLOAD_BASE_DIR+DateUtil.stampToDate(System.currentTimeMillis(), "yyyy/MM/dd");
String abspath = servletContext.getRealPath(realPath);
File uploadDir = new File(abspath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
String fileName = randName()+".jpg";
Base64File.generateImage(file, abspath+"/"+fileName);
data.setData(fileName);
data.setResult(0);
MyLogUtils.getInstance().log("上传图片成功");
} catch (Exception e) {
e.printStackTrace();
data.setErrMsg("图片服务器服务繁忙");
} return data;
}
有时候咱们遇到用户上传的图片很大,那么我们就需要压缩图片并保留原图,代码如下
@RequestMapping(value="imgFileCompress",method=RequestMethod.POST)
@ResponseBody
public Json uploadFileAndCreateThumbnail(@RequestParam("file") CommonsMultipartFile imageFile) {
Json data = new Json();
data.setResult(0);
if(imageFile == null ){
data.setErrMsg("imageFile不能为空");
return data;
}
if (imageFile.getSize() >= 10*1024*1024){
data.setErrMsg("文件不能大于10M");
return data;
}
//拼接后台文件名称
String pathName = randName() + "." + FilenameUtils.getExtension(imageFile.getOriginalFilename()); //文件存放路径
String realPaths = Config.UPLOAD_BASE_DIR+"/"+DateUtil.stampToDate(System.currentTimeMillis(), "yyyy/MM/dd"); //构建保存文件路径
String realPath = servletContext.getRealPath(realPaths); //拼接文件路径
String filePathName = realPath + File.separator + pathName; System.out.println("图片上传路径:"+filePathName);
//判断文件保存是否存在
File file = new File(filePathName);
if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
//创建文件 file.getParentFile().mkdirs();
}
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
inputStream = imageFile.getInputStream();
fileOutputStream = new FileOutputStream(file);
//写出文件
byte[] buffer = new byte[2048];
IOUtils.copyLarge(inputStream, fileOutputStream, buffer);
buffer = null;
} catch (IOException e) {
filePathName = null;
data.setErrMsg("操作失败");
e.printStackTrace();
return data;
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (IOException e) {
filePathName = null;
data.setErrMsg("操作失败");
return data;
}
}
/*** 缩略图begin*/
//拼接后台文件名称
String thumbnailPathName = randName() + "small." + FilenameUtils.getExtension(imageFile.getOriginalFilename()); if(thumbnailPathName.contains(".png")){
thumbnailPathName = thumbnailPathName.replace(".png", ".jpg");
}
long size = imageFile.getSize();
double scale = 1.0d ;
if(size >= 200*1024){
if(size > 0){
scale = (200*1024f) / size ;
}
}
//拼接文件路径
String thumbnailFilePathName = realPath + File.separator + thumbnailPathName;
try {
if(size < 200*1024){
Thumbnails.of(filePathName).scale(1f).outputFormat("jpg").toFile(thumbnailFilePathName);
}else{
Thumbnails.of(filePathName).scale(1f).outputQuality(scale).outputFormat("jpg").toFile(thumbnailFilePathName);
}
} catch (Exception e1) {
data.setErrMsg("操作失败");
return data;
}
/*** 缩略图end*/
Map map = new HashMap();
//原图地址
map.put("originalUrl", pathName);
//缩略图地址
map.put("thumbnailUrl", thumbnailPathName);
data.setData(map);
data.setResult(1);
return data;
}
附加:base64 与 图片之间的互相转换
1.图片转Base64
/** * @Description: 根据图片地址转换为base64编码字符串
* @Author: * @CreateTime: * @return */
public static String getImageStr(String imgFile) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
2.base64 转 图片
/** * @Description: 将base64编码字符串转换为图片 * @Author: * @CreateTime:
* @param imgStr base64编码字符串 * @param path 图片路径-具体到文件 * @return */
public static boolean generateImage(String imgStr, String path) {
if (imgStr == null){
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
// 解密
byte[] b = decoder.decodeBuffer(imgStr);
// 处理数据
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) { b[i] += 256;
}
}
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
}catch(Exception ex){
return false;
}
}