文件上传代码实现

1、文件上传的三要素:

  • 表单提交的方式必须是POST
  • 表单中需要有文件上传项,文件上传项必须有name值<input type="file" name="upload"/>
  • 表单的enctype的属性必须是multipart/form-data

2、提供三个成员属性

/**
	 * 文件上传提供的三个属性
	 */
	private String uploadFileName;//文件名称
	private File upload;//上传文件
	private String uploadContentType;//文件类型
	
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

3、文件上传的工具类

package com.itheima.crm.utils;

import java.util.UUID;

/**
 * 文件上传的工具类
 * @author tycoon
 *
 */
public class UploadUtils {

	/**
	 * 解决目录下文件名重复的问题了
	 * @param fileName
	 * @return
	 */
	public static String getUuidFileName(String fileName){
		
		int idx=fileName.lastIndexOf(".");//aa.txt
		String extions=fileName.substring(idx);
		return UUID.randomUUID().toString().replace("-", "");
	}
	
	/**
	 * 目录分离的方法
	 */
	public static String getPath(String uuidFileName){
		int code1=uuidFileName.hashCode();
		int d1=code1 & 0xf;//作为一级目录
		int code2=code1>>>4;
		int d2=code2 & 0xf;//作为二级目录
		return "/"+d1+"/"+d2;
	}
}

4、上传具体实现

	public String save() throws IOException{
		//上传图片
		if(upload!=null){
			//文件上传
			//设置文件上传的路径
			String path="C:/upload";
			//一个目录下存放相同的文件名:随机文件名
			String uuidFileName=UploadUtils.getUuidFileName(uploadFileName);
			//一个目录下存放的文件过多:目录分离
			String realPath=UploadUtils.getPath(uuidFileName);
			//创建目录
			String url=path+realPath;
			File file=new File(url);
			
			if(!file.exists()){
				file.mkdirs();
			}
			//文件上传
			File dictFile=new File(url+"/"+uuidFileName);
			FileUtils.copyFile(upload, dictFile);
		}
		
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值