欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java 文件上传重要代码教程,java文件上传教程

来源: javaer 分享于  点击 11522 次 点评:21

Java 文件上传重要代码教程,java文件上传教程


1、上传实体工具类:

public class FileUpload {
 private String fileName;	//文件名
 private String filePath;	//文件路径
 private String [] allowType = {"jpg", "jpeg", "bmp" , "png", "gif", "zip", "xlsx", "apk","bin"};	 //允许的文件类型
 private Integer maxSize = 2 * 1024 * 1024;	//文件最大值,默认4M
 private Integer minSize = 1;	//文件最小值,默认1B

 /**
  * 默认构造方法
  */
 public FileUpload() {}
	
 /**
  * 设置参数
  * @param fileName 文件名
  * @param filePath 文件路径
  * @param allowType 允许的文件类型
  * @param maxSize 文件最大值
  * @param minSize 文件最小值
  */
 public FileUpload(String fileName, String filePath, String[] allowType, Integer maxSize, Integer minSize) {
 if(fileName != null){
  this.fileName = fileName;
 }
 if(filePath != null){
  this.filePath = filePath;
 }
 if(allowType != null){
  this.allowType = allowType;
 }
 if(filePath != null){
  this.maxSize = maxSize;
 }
 if(minSize != null){
  this.minSize = minSize;
 }
}

2、生成随机字符串工具类:

public class RandomUtil {

 public static String getRandomString(int length, int type) {  // length表示生成字符串的长度
  String base0 = "0123456789";
  String base1 = "abcdefghijklmnopqrstuvwxyz";
  String base2 = "abcdefghijklmnopqrstuvwxyz0123456789";
  String base3 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  String base = "";
	if (type == 0) {
		base = base0;
	}
	if (type == 1) {
		base = base1;
	}
	if (type == 2) {
		base = base2;
	}
	if (type == 3) {
		base = base3;
	}
	Random random = new Random();
	StringBuffer sb = new StringBuffer();
	for (int i = 0; i < length; i++) {
		int number = random.nextInt(base.length());
		sb.append(base.charAt(number));
	}
	return sb.toString();
 }
}

3、上传处理工具类:

public class UploadUtil {
	
 static Logger logger = LoggerFactory.getLogger(UploadUtil.class);	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS"); 


	public static String uploadFile(File file, FileUpload fileUpload) throws AppValidationException{
		return uploadFile(file, fileUpload, false);
	}

	public static String uploadFile(File file, FileUpload fileUpload, boolean fillRandom) 
throws AppValidationException{
		String newFileName = null;
		try {
			if(fileUpload == null){
				logger.debug("文件参数不能为空!");
			}else{
				if(fileUpload.getFilePath() == null){
					logger.debug("文件上传路径不能为空!");
				}else{
					String savePath = fileUpload.getFilePath(); //获取Struts临时上传路径名
					if(fileUpload.getFileName() == null){
						logger.debug("文件名称不能为空!");
					}else{
						String fileName = fileUpload.getFileName();	 //文件名					 					
						String extName = "";	//文件后缀名													 
						boolean flag = false;
						if(fileName.indexOf(".") != -1 && fileName.lastIndexOf(".") != 0){
							extName = fileName.substring(fileName.lastIndexOf(".") + 1);
							for(String type : fileUpload.getAllowType()){
								if(type.equalsIgnoreCase(extName)){
									flag = true;
									break;
								}
							}
							if(!flag){
								logger.debug("不允许上传的文件格式!");
								throw new AppValidationException(ExceptionConstants.UPLOAD_PATTERN_ERROR, "");
							}else{
								// 设置文件存放目录
								File directory = new File(fileUpload.getFilePath());
								if(!directory.exists() || !directory.isDirectory()){
									directory.mkdirs();
								}
								if (!fillRandom){
									newFileName = sdf.format(new Date()) + "." + extName;
								}else{
									newFileName = sdf.format(new Date()) + RandomUtil.getRandomString(3, 3) + "." + extName;
 }  
								logger.info("Upload file name:"+newFileName);
								File newFile = new File(savePath, newFileName);
								FileUtils.copyFile(file, newFile);
								logger.debug("文件大小不符合!");
							}
						}else{
							logger.debug("文件格式有误!");
						}
					}
				}
			}
		} catch (AppValidationException e) {
			throw new AppValidationException(ExceptionConstants.UPLOAD_PATTERN_ERROR, "");
		} catch (Exception e) {
			logger.error("上传异常!!");
			e.printStackTrace();
		}
		return newFileName;
	}
}
相关栏目:

用户点评