最近学到的web阶段的文件的上传,就想记录一下,帮助自己复习以及帮助大家学习,一般我都会把上传的文件存到服务器中的web-inf 下面,因为这样用户不会直接访问到,我们存到数据库的一般都是路径。这里没有演示数据库上传路径,气势上传路径很简单,只需要你把路径和文件名插入到数据库中的某个表就可以了,等你到时候想用找到文件的时候,就从数据库中查找路径就行了。废话不说,上代码(上传文件的servlet,前台界面只需要有一个类型为file的 input标签,如果想一次选上传多个,可以多写几个input或者在input标签内 增加multiple="multiple" 属性,就可以实现一个input中写入好几个文件):
package practice;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//判断表单上传的方式 是否是 multipart/form-data;
boolean ismultipartContent = ServletFileUpload.isMultipartContent(request);
if(!ismultipartContent){
throw new RuntimeException("your form is not multipart/form-data");
}
//创建一个DiskFileItemFactory工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
//创建一个临时文件存储的目录
String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
File tempFile = new File(tempPath);
if(!tempFile.exists()){
tempFile.mkdir();
}
factory.setRepository(tempFile);
//创建ServletFileUoload 核心对象
ServletFileUpload sfu = new ServletFileUpload(factory);
//解决文件上传乱码问题
sfu.setHeaderEncoding("utf-8");
try {
sfu.setFileSizeMax(1024*1024*3); //单个文件大小
sfu.setSizeMax(1024*1024*6); //总文件大小
//遍历表单集合返回一个List<FileItem>集合
List<FileItem> fileItems = sfu.parseRequest(request);
for(FileItem fileItem:fileItems){
//判断是普通表单还是上传表单
if(fileItem.isFormField()){
//按照普通表单处理
processFormField(fileItem);
}else{
//按照上传表单来处理
processUploadField(fileItem);
}
}
}catch(FileUploadBase.FileSizeLimitExceededException e){
e.printStackTrace();
request.setAttribute("message", "单个文件超出最大值");
request.getRequestDispatcher("/uploadSong.jsp").forward(request, response);
return;
}catch(FileUploadBase.SizeLimitExceededException e){
e.printStackTrace();
request.setAttribute("message", "上传文件的总大小超出限制");
request.getRequestDispatcher("/uploadSong.jsp").forward(request, response);
return;
}
catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //遍历表单项集合
}
//处理上传文件的函数
private void processUploadField(FileItem fileItem) {
//得到上传文件的名字
String filename = fileItem.getName();
//得到文件输入流
try {
InputStream is = fileItem.getInputStream();
//将文件保存在服务器上
String directoryRealPath =this.getServletContext().getRealPath("/WEB-INF/upload");//创建的路径
File storeDirectory = new File(directoryRealPath);
if(!storeDirectory.exists()){
storeDirectory.mkdir(); //创建一个指定目录
}
//处理文件名
//filename =filename.substring(filename.lastIndexOf(File.separator)+1);
if(filename!=null){
filename=FilenameUtils.getName(filename);
}
//不让文件名重复
filename=UUID.randomUUID()+"_"+filename;
//打散目录
String childDirectory = makChildDirectory(storeDirectory,filename);
//构建一个完整的文件路径
/*File file =new File(storeDirectory,childDirectory+File.separator+filename);
//创建一个写的流,将图片写入路径
FileOutputStream fos = new FileOutputStream(file);
int len=0;
byte [] buf = new byte[1024];
while((len=is.read(buf))!=-1){
fos.write(buf,0,len);
}
fos.close();
is.close();*/
//用工具类实现文件上传操作
fileItem.write(new File(storeDirectory,childDirectory+File.separator+filename));
fileItem.delete();//删除临时文件
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//打散目录
private String makChildDirectory(File storeDirectory, String filename) {
int hashcode = filename.hashCode();
//把hashcode转换成16进制
String code = Integer.toHexString(hashcode);
String childDirectory = code.charAt(0)+File.separator+code.charAt(1);
File file = new File(storeDirectory,childDirectory);
if(!file.exists()){
file.mkdirs();
}
return childDirectory;
}
//处理普通表单的函数
private void processFormField(FileItem fileItem) {
//解决文件名字乱码问题
try {
String fieldName = fileItem.getFieldName(); //获取字段名
//String fieldValue = fileItem.getString(); //获取值
String fieldValue = fileItem.getString("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}