java上传文件工具类

java 2017-07-28

这个是之前整理之前所学时与使用java向邮箱发送邮件一块找到的,一起贴出来供大家参考:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.apache.struts.upload.FormFile;
import org.apache.struts.util.MessageResources;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UploadFile {
 
 /**
  * 按照ID和当前时间生成目录
  * @param OrderId
  * @return
  */
 public static String getAbsolutePath(){
  String currYear= new SimpleDateFormat("yyyy").format(new Date());
  String currMonth= new SimpleDateFormat("MM").format(new Date());
  String currDay = new SimpleDateFormat("dd").format(new Date());
  String path = new StringBuffer(currYear).append('/').append(currMonth).append('/').append(currDay).append('/').toString();
  return path;
  }

 /**
  * 上传课程资料
  * @param dir 文件目录
  * @param trueName 文件名称
  * @param formFile FormFile
  * @return String
  * @throws Exception
  */
 public static String uploadFile(int courseId,String dir,FormFile file,MessageResources message) throws Exception {
  String fileName = file.getFileName();
  int i = fileName.lastIndexOf(".");
  String logoFormat = fileName.substring(i + 1);
  int size = file.getFileSize();
  // *************限制文件的上传格式和文件大小*******************
  String fileFormat = message.getMessage("file.fileFormat"); // 文件格式
  int imageSize = Integer.valueOf(message.getMessage("file.fileSize"));// 文件大小
  String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
  if (format != null && size <= imageSize) {
   fileName = courseId+"_"+String.valueOf(System.currentTimeMillis()) + "." + logoFormat;
   File dirPath = new File(dir + "/" + fileName);// 存储位置
   mkdirIfNotExists(dirPath);
   InputStream streamIn = file.getInputStream(); // 创建读取用户上传文件的对象
   File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
   // 判断指定路径是否存在,不存在则创建路径
   if (!uploadFile.exists() || uploadFile == null) {
    uploadFile.mkdirs();
   }
   OutputStream streamOut = new FileOutputStream(dirPath);
   int bytesRead = 0;
   byte[] buffer = new byte[8192];
   while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
    streamOut.write(buffer, 0, bytesRead);
   }
   streamOut.close();
   streamIn.close();
   file.destroy();
   return fileName;
  }else{
   return null;
  }
 }
 
 /**
  * 上传文章附件
  * @param dir
  * @param file
  * @param message
  * @return
  * @throws Exception
  */
 public static String uploadFile(String dir,FormFile file,MessageResources message) throws Exception {
  String fileName = file.getFileName();
  int i = fileName.lastIndexOf(".");
  String logoFormat = fileName.substring(i + 1);
  int size = file.getFileSize();
  // *************限制文件的上传格式和文件大小*******************
  String fileFormat = message.getMessage("file.fileFormat"); // 文件格式
  int imageSize = Integer.valueOf(message.getMessage("file.fileSize"));// 文件大小
  String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
  if (format != null && size <= imageSize) {
   fileName = String.valueOf(System.currentTimeMillis()) + "." + logoFormat;
   File dirPath = new File(dir + "/" + fileName);// 存储位置
   mkdirIfNotExists(dirPath);
   InputStream streamIn = file.getInputStream(); // 创建读取用户上传文件的对象
   File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
   // 判断指定路径是否存在,不存在则创建路径
   if (!uploadFile.exists() || uploadFile == null) {
    uploadFile.mkdirs();
   }
   OutputStream streamOut = new FileOutputStream(dirPath);
   int bytesRead = 0;
   byte[] buffer = new byte[8192];
   while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
    streamOut.write(buffer, 0, bytesRead);
   }
   streamOut.close();
   streamIn.close();
   file.destroy();
   return fileName;
  }else{
   return null;
  }
 }
 
 
 public static String uploadFile1(String dir,FormFile file,MessageResources message) throws Exception {
  String fileName = file.getFileName();
  String s=UUID.randomUUID().toString();
  int i = fileName.lastIndexOf(".");
  String logoFormat = fileName.substring(i + 1);
  int size = file.getFileSize();
  // *************限制文件的上传格式和文件大小*******************
  String fileFormat = message.getMessage("file.fileFormat"); // 文件格式
  int imageSize = Integer.valueOf(message.getMessage("file.fileSize"));// 文件大小
  String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
  if (format != null && size <= imageSize) {
   fileName = String.valueOf(System.currentTimeMillis()+s) + "." + logoFormat;
   File dirPath = new File(dir + "/" + fileName);// 存储位置
   mkdirIfNotExists(dirPath);
   InputStream streamIn = file.getInputStream(); // 创建读取用户上传文件的对象
   File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
   // 判断指定路径是否存在,不存在则创建路径
   if (!uploadFile.exists() || uploadFile == null) {
    uploadFile.mkdirs();
   }
   OutputStream streamOut = new FileOutputStream(dirPath);
   int bytesRead = 0;
   byte[] buffer = new byte[8192];
   while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
    streamOut.write(buffer, 0, bytesRead);
   }
   streamOut.close();
   streamIn.close();
   file.destroy();
   return fileName;
  }else{
   return null;
  }
 }
 
 
 /**
  * @param 文件扩展名
  * @param permitFormatsConfig 文件类型
  * @return String 文件匹配类型
  */
 public static String checkFileExt(String type, String permitFormatsConfig) {
  String[] formats = permitFormatsConfig.split(";");
  for (int i = 0; i < formats.length; i++) {
   if (type.toLowerCase().endsWith(formats[i].toLowerCase())) {
    return formats[i];
   }
  }
  return null;
 }
 public static File mkdirIfNotExists(File file) {
  if (file.exists()) {
   return file;
  }
  if (file.isDirectory() && file.mkdirs()) {
   return file;
  }
  File parentDirectory = file.getParentFile();
  if (parentDirectory.exists()) {
   return file;
  } else if (parentDirectory.mkdirs()) {
   return file;
  }
  throw new java.lang.RuntimeException(
    "Failed to make some necessary parent directories. Please trying.");
 }
 
 /**
  * 上传图片,并获得缩小图片
  * 图片大小交由显示页面控制 后台将不负责修改图像大小
  * @param picDir
  * @param file
  * @param message
  * @param width
  * @return
  * @throws Exception
  */
 public static String uploadFile(String picDir, FormFile file,
   MessageResources message, int width,int height) throws Exception {
  String fileName = file.getFileName();
  int ff = fileName.lastIndexOf(".");
  ImageScale imageScale = new ImageScale();
  String logoFormat = fileName.substring(ff + 1);
  int size = file.getFileSize();
  // *************限制文件的上传格式和文件大小*******************
  String fileFormat = message.getMessage("file.imageFormat"); // 文件格式
  int imageSize = Integer.valueOf(message
    .getMessage("file.imageSize"));// 文件大小
  String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
  if (format != null && size <= imageSize) {
   fileName = String.valueOf(System.currentTimeMillis()) + "." + logoFormat;
   File dirPath = new File(picDir + "/" + fileName);
   mkdirIfNotExists(dirPath);// 存储位置
   InputStream stream = file.getInputStream();
   OutputStream bos = new FileOutputStream(dirPath);
   BufferedImage Bi = ImageIO.read(file.getInputStream());
   bos = new FileOutputStream(dirPath);
   //图片大小交由显示页面控制 后台将不负责修改图像大小
   /*if (Bi.getWidth() > width || Bi.getHeight() > height) {
    Bi = imageScale.imageZoomOut(Bi, width, height);
    ImageIO.write(Bi, logoFormat, dirPath);
   } else {*/
    ImageIO.write(Bi, logoFormat, dirPath);
   //}
   bos.close();
   stream.close();
   file.destroy();
   return fileName;
  } else {
   file.destroy();
   return null;
  }
 }
 
 /**
  * 上传图片,并获得缩小图片
  * @param picDir
  * @param file
  * @param message
  * @param width
  * @return
  * @throws Exception
  */
 public static String uploadFile(String picDir, FormFile file,MessageResources message, int width) throws Exception {
  String fileName = file.getFileName();
  int ff = fileName.lastIndexOf(".");
  ImageScale imageScale = new ImageScale();
  String logoFormat = fileName.substring(ff + 1);
  int size = file.getFileSize();
  // *************限制文件的上传格式和文件大小*******************
  String fileFormat = message.getMessage("file.imageFormat"); // 文件格式
  int imageSize = Integer.valueOf(message.getMessage("file.imageSize"));// 文件大小
  String format = UploadFile.checkFileExt(logoFormat, fileFormat); // 判断文件格式
  if (format != null && size <= imageSize) {
   fileName = String.valueOf(System.currentTimeMillis()) + "."+ logoFormat;
   File dirPath = new File(picDir + "/" + fileName);// 存储位置
   mkdirIfNotExists(dirPath);
   InputStream stream = file.getInputStream();
   OutputStream bos = new FileOutputStream(dirPath);
   BufferedImage Bi = ImageIO.read(file.getInputStream());
   if (Bi.getWidth() > width || Bi.getHeight() > width) {
    Bi = imageScale.imageZoomOut(Bi, width, width);
    ImageIO.write(Bi, logoFormat, dirPath);
   } else {
    ImageIO.write(Bi, logoFormat, dirPath);
   }
   bos.close();
   stream.close();
   file.destroy();
   dirPath = new File(picDir + "/hoy_" + fileName);
   bos = new FileOutputStream(dirPath);
   if (Bi.getWidth() > 142 || Bi.getHeight() > 60) {
    Bi = imageScale.imageZoomOut(Bi, 142, 60);
    ImageIO.write(Bi, logoFormat, dirPath);
   } else {
    ImageIO.write(Bi, logoFormat, dirPath);
   }
   bos.close();
   stream.close();
   file.destroy();
   return fileName;
  } else {
   file.destroy();
   return null;
  }
 }
}
 

本文由 admin 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

8 条评论

  1. oshhiizwer
    oshhiizwer

    java上传文件工具类 - 青花瓷
    aoshhiizwer
    oshhiizwer http://www.g0lq1601pdlcafxs2qe4i10140z43t75s.org/
    [url=http://www.g0lq1601pdlcafxs2qe4i10140z43t75s.org/]uoshhiizwer[/url]

  2. ztzzocgvex
    ztzzocgvex

    java上传文件工具类 - 青花瓷
    ztzzocgvex http://www.g825ts137v9fd6lr9aux3hd0f3676p4us.org/
    aztzzocgvex
    [url=http://www.g825ts137v9fd6lr9aux3hd0f3676p4us.org/]uztzzocgvex[/url]

  3. qypiommhmi
    qypiommhmi

    java上传文件工具类 - 青花瓷
    [url=http://www.g1es27e3s924667vcz39w9e50dpzhho3s.org/]uqypiommhmi[/url]
    qypiommhmi http://www.g1es27e3s924667vcz39w9e50dpzhho3s.org/
    aqypiommhmi

  4. dpprefskbw
    dpprefskbw

    java上传文件工具类 - 青花瓷
    dpprefskbw http://www.g361kc28e36hlrk4k1f9llwktf374580s.org/
    [url=http://www.g361kc28e36hlrk4k1f9llwktf374580s.org/]udpprefskbw[/url]
    adpprefskbw

  5. krrtvmpoie
    krrtvmpoie

    java上传文件工具类 - 青花瓷
    [url=http://www.gh7h2g268g22482eg85ft988vzqeggq1s.org/]ukrrtvmpoie[/url]
    krrtvmpoie http://www.gh7h2g268g22482eg85ft988vzqeggq1s.org/
    akrrtvmpoie

  6. bgjwgidmkv
    bgjwgidmkv

    java上传文件工具类 - 青花瓷
    bgjwgidmkv http://www.gl253i3gg4zop81h2km89a1c4917jcd6s.org/
    abgjwgidmkv
    [url=http://www.gl253i3gg4zop81h2km89a1c4917jcd6s.org/]ubgjwgidmkv[/url]

  7. http://viagrabs.com/
    http://viagrabs.com/

    sildenafil and extacy [url=http://viagrabs.com/]buy sildenafil[/url] co may loai thuoc sildenafil.

  8. cialisle.com
    cialisle.com

    testimonials on tadalafil [url=http://cialisle.com/]cialis online[/url] dosierung
    viagra cialis.

添加新评论