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