单张,多张图片上传工具类

package org.lchq.file;






import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;


import javax.servlet.http.HttpServletRequest;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.lchq.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;


/**
 * 文件上传,
 * @author lchq
 *
 */
public class FileUtil {


private static Logger logger = Logger.getLogger(FileUtil.class);

public static String[] pics = { "BMP", "PCX", "TIFF", "GIF", "JPEG", "TGA",
"EXIF", "FPX", "SVG", "PSD", "CDR", "PCD", "DXF", "UFO", "EPS",
"AI", "PNG", "HDRI", "RAW", "JPG" };


/**
* validFile(这里用一句话描述这个方法的作用) (图片验证,大小10m)

* @return
* @exception
* @since 1.0.0
*/
public static String validFile(MultipartFile obj) {

String str=null;
try {


MultipartFile f = (MultipartFile) obj;
if (f.getSize() > 10000000) {
return str="文件大小不得超过10M";
}
String extName = f.getOriginalFilename().substring(
f.getOriginalFilename().lastIndexOf(".") + 1);
if (!Arrays.asList(FileUtil.pics).contains(extName.toUpperCase())) {
return str="非图片文件";
}
str="校验通过";
} catch (Exception e) {
throw e;
}
return str;
}


public static String upload(HttpServletRequest request, String basePath) {


try {
request.setCharacterEncoding("utf-8");// 防止中文名乱码
int sizeThreshold = 1024 * 6; // 缓存区大小
File repository = new File(basePath); // 缓存区目录
long sizeMax = 1024 * 1024 * 2;// 设置文件的大小为2M
final String allowExtNames = "jpg,gif,bmp,rar,rar,txt,docx";
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(repository);
diskFileItemFactory.setSizeThreshold(sizeThreshold);
ServletFileUpload servletFileUpload = new ServletFileUpload(
diskFileItemFactory);
servletFileUpload.setSizeMax(sizeMax);


List<FileItem> fileItems = null;


fileItems = servletFileUpload.parseRequest(request);


for (FileItem fileItem : fileItems) {
if (!fileItem.isFormField()) {
long size = 0;
String filePath = fileItem.getName();
System.out.println(filePath);
if (filePath == null || filePath.trim().length() == 0)
continue;
String fileName = String
.valueOf(System.currentTimeMillis());
String extName = filePath.substring(filePath
.lastIndexOf(".") + 1);
fileName += "." + extName;
if (allowExtNames.indexOf(extName) != -1) {
try {
fileItem.write(new File(basePath + File.separator
+ fileName));
} catch (Exception e) {
e.printStackTrace();
}
} else {
throw new FileUploadException(
"file type is not allowed");
}
}
}
} catch (FileSizeLimitExceededException e) {
System.out.println("file size is not allowed");
} catch (FileUploadException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}


return null;


}


/**
* 文件上传

* @param f
*            文件对象
* @param baseDri
*            文件存放目录
* @return 文件名
*/
public static String upload1(MultipartFile f, String baseDri,
HttpServletRequest request) {
String basedri = request.getSession().getServletContext()
.getRealPath("/");

try {
if (f.isEmpty()) {
logger.info("文件未上传");
} else {
logger.info("文件长度: " + f.getSize());
logger.info("文件类型: " + f.getContentType());
logger.info("文件名称: " + f.getName());
logger.info("文件原名: " + f.getOriginalFilename());
logger.info("========================================");

String fileName =  f.getOriginalFilename();

String baseurl=baseDri+DirUtils.getDir(fileName);
String parentUrl=basedri+baseurl;
           //生成文件名
String name = StringUtils
.getTimeMillis("yyyyMMddHHmmSSS", 7);
String extName = fileName.substring(fileName
.lastIndexOf(".") + 1);
name += "." + extName;
//设置目标文件
File fil =new File(parentUrl);
                
if (!fil.exists()) {
fil.mkdirs();
}

File file=new File(parentUrl,name);
System.out.println(parentUrl);
//创建一个输入流
         InputStream is = f.getInputStream();              
       //使用输出流来包装目标文件
       OutputStream os = new FileOutputStream(file);
       byte[] buffer = new byte[1024];
       int length = 0;
       while((length = is.read(buffer)) > 0) {
           os.write(buffer, 0, length);
       }
       //关闭输入流
       is.close();
       //关闭输出流
       os.close();
       return baseurl+"/"+name;
}
} catch (IOException e) {
logger.info("文件上传失败", e);
}
return "";
}


/**
* 文件上传

* @param obj
*            文件对象
* @param baseDri
*            文件存放目录
* @return 文件名
*/
public static String upload2(Object myPic, String baseDri,
HttpServletRequest request) {
String basedri1 = request.getSession().getServletContext()
.getRealPath("/");
String pic = "";
try {
if (myPic != null) {
if (myPic instanceof Object[]) {
Object[] myPics = (Object[]) myPic;
if (myPics != null && myPics.length > 0) {


for (Object obj : myPics) {
if (obj != "" && obj != null) {
if (obj instanceof MultipartFile) {
MultipartFile f = (MultipartFile) obj;
String url = FileUtil.upload1(f, baseDri,
request);
if (StringUtils.isNull(pic)) {
if (!StringUtils.isNull(url)) {
pic = pic + url;
}
} else {
if (!StringUtils.isNull(url)) {
pic = pic + ";" + url;
}
}
}
}
}
}
} else if (myPic instanceof List) {
List myPics = (List) myPic;
if (myPics != null && myPics.size() > 0) {


for (Object obj : myPics) {
if (obj != "" && obj != null) {
if (obj instanceof MultipartFile) {
MultipartFile f = (MultipartFile) obj;
String url = FileUtil.upload1(f, baseDri,
request);
if (StringUtils.isNull(pic)) {
if (!StringUtils.isNull(url)) {
pic = pic + url;
}
} else {
if (!StringUtils.isNull(url)) {
pic = pic + ";" + url;
}
}
}
}
}
}
} else {
if (myPic != "" && myPic != null) {
if (myPic instanceof MultipartFile) {
MultipartFile f = (MultipartFile) myPic;
pic = upload1(f, baseDri, request);
}
}
}
} else {
pic = null;
}
} catch (Exception e) {
logger.info("文件上传失败", e);
}
return pic;
}


/**
*  文件上传

* @param obj
*            文件对象
* @param baseDri
*            文件存放目录
* @return 文件名
*/
public static String upload3(Object myPic, String baseDri,
HttpServletRequest request) {
String pic = "";
try {
if (myPic != null) {
if (myPic instanceof Object[]) {
Object[] myPics = (Object[]) myPic;
if (myPics != null && myPics.length > 0) {


for (Object obj : myPics) {
if (obj != "" && obj != null) {
if (obj instanceof MultipartFile) {
MultipartFile f = (MultipartFile) obj;
String url = FileUtil.upload2(f, baseDri,
request);
if (StringUtils.isNull(pic)) {
if (!StringUtils.isNull(url)) {
pic = pic + url;
}
} else {
if (!StringUtils.isNull(url)) {
pic = pic + ";" + url;
}
}
}
}
}
}
} else if (myPic instanceof List) {
List myPics = (List) myPic;
if (myPics != null && myPics.size() > 0) {


for (Object obj : myPics) {
if (obj != "" && obj != null) {

if (obj instanceof MultipartFile) {
MultipartFile f = (MultipartFile) obj;
String url = FileUtil.upload2(f, baseDri,
request);
if (StringUtils.isNull(pic)) {
if (!StringUtils.isNull(url)) {
pic = pic + url;
}
} else {
if (!StringUtils.isNull(url)) {
pic = pic + ";" + url;
}
}
}
}
}
}
} else {
if (myPic != "" && myPic != null) {
if (myPic instanceof MultipartFile) {

MultipartFile f = (MultipartFile) myPic;
pic = upload2(f, baseDri, request);
}
}
}
} else {
pic = null;
}
} catch (Exception e) {
logger.info("文件上传失败", e);
}
return pic;
}


/**
 * 根据文件名生成文件目�?
 * @author Administrator
 *
 */
public class DirUtils {
public static String getDir(String name) {
if (name != null) {
int code = name.hashCode();
// /10/5
return "/" + (code & 15) + "/" + (code >>> 4 & 15);
}
return null;
}


}



public static void main(String[] args) throws IOException {


}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值