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;
	}
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值