JSP文件上传
好久没有用到文件上传了,很多的细节都忘记了,今天学习了一下,与大家分享,首先来看下性能较高的COS。
关于cos的历史就不啰嗦了,大家在Google一下就可以找到很多,主要来看下他的用法,在jsp中:
<form enctype="multipart/form-data" method = "post" action = "UploadServlet.do">
<input type="text" name="userName" />
<p>上传文件1:<input type = "file" name = "File1" size = "20" maxlength = "20"><br>
<p>上传文件2:<input type = "file" name = "File2" size = "20" maxlength = "20"><br>
<p>上传文件3:<input type = "file" name = "File3" size = "20" maxlength = "20"><br>
<p>上传文件4:<input type = "file" name = "File4" size = "20" maxlength = "20"><br>
<input type = "submit" value = "上传">
</form>
<input type="text" name="userName" />
<p>上传文件1:<input type = "file" name = "File1" size = "20" maxlength = "20"><br>
<p>上传文件2:<input type = "file" name = "File2" size = "20" maxlength = "20"><br>
<p>上传文件3:<input type = "file" name = "File3" size = "20" maxlength = "20"><br>
<p>上传文件4:<input type = "file" name = "File4" size = "20" maxlength = "20"><br>
<input type = "submit" value = "上传">
</form>
然后在UploadServlet中:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//存绝对路径
//String filePath = "C://upload";
//存相对路径
String filePath = getServletContext().getRealPath("/")+"upload";
File uploadPath = new File(filePath);
//检查文件夹是否存在 不存在 创建一个
if(!uploadPath.exists())
{
uploadPath.mkdir();
}
//文件最大容量 5M
int fileMaxSize = 5*1024*1024;
//存放文件描述
String[] fileDiscription = {null,null};
//文件名
String fileName = null;
//上传文件数
int fileCount = 0;
//重命名策略
RandomFileRenamePolicy rfrp=new RandomFileRenamePolicy();
//上传文件
MultipartRequest mulit = new MultipartRequest(request,filePath,fileMaxSize,"UTF-8",rfrp);
String userName = mulit.getParameter("userName");
System.out.println(userName);
Enumeration filesname = mulit.getFileNames();
while(filesname.hasMoreElements()){
String name = (String)filesname.nextElement();
fileName = mulit.getFilesystemName(name);
String contentType = mulit.getContentType(name);
if(fileName!=null){
fileCount++;
}
System.out.println("文件名:" + fileName);
System.out.println("文件类型: " + contentType);
}
System.out.println("共上传" + fileCount + "个文件!");
}
throws ServletException, IOException {
//存绝对路径
//String filePath = "C://upload";
//存相对路径
String filePath = getServletContext().getRealPath("/")+"upload";
File uploadPath = new File(filePath);
//检查文件夹是否存在 不存在 创建一个
if(!uploadPath.exists())
{
uploadPath.mkdir();
}
//文件最大容量 5M
int fileMaxSize = 5*1024*1024;
//存放文件描述
String[] fileDiscription = {null,null};
//文件名
String fileName = null;
//上传文件数
int fileCount = 0;
//重命名策略
RandomFileRenamePolicy rfrp=new RandomFileRenamePolicy();
//上传文件
MultipartRequest mulit = new MultipartRequest(request,filePath,fileMaxSize,"UTF-8",rfrp);
String userName = mulit.getParameter("userName");
System.out.println(userName);
Enumeration filesname = mulit.getFileNames();
while(filesname.hasMoreElements()){
String name = (String)filesname.nextElement();
fileName = mulit.getFilesystemName(name);
String contentType = mulit.getContentType(name);
if(fileName!=null){
fileCount++;
}
System.out.println("文件名:" + fileName);
System.out.println("文件类型: " + contentType);
}
System.out.println("共上传" + fileCount + "个文件!");
}
注意的是文件重命名策略,我们需要实现FileRenamePolicy接口中的rename方法:
package com.kay.util;
import java.io.File;
import java.util.Date;
import com.oreilly.servlet.multipart.FileRenamePolicy;
public class RandomFileRenamePolicy implements FileRenamePolicy {
@Override
public File rename(File file) {
String body="";
String ext="";
Date date = new Date();
int pot=file.getName().lastIndexOf(".");
if(pot!=-1){
body= date.getTime() +"";
ext=file.getName().substring(pot);
}else{
body=(new Date()).getTime()+"";
ext="";
}
String newName=body+ext;
file=new File(file.getParent(),newName);
return file;
}
}
import java.io.File;
import java.util.Date;
import com.oreilly.servlet.multipart.FileRenamePolicy;
public class RandomFileRenamePolicy implements FileRenamePolicy {
@Override
public File rename(File file) {
String body="";
String ext="";
Date date = new Date();
int pot=file.getName().lastIndexOf(".");
if(pot!=-1){
body= date.getTime() +"";
ext=file.getName().substring(pot);
}else{
body=(new Date()).getTime()+"";
ext="";
}
String newName=body+ext;
file=new File(file.getParent(),newName);
return file;
}
}
cos的上传比较简单,但是我还没有发现怎么过滤文件后缀,知道的朋友给说下,所以我又看了JSPSmartLoad组件:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//文件上传个数
int count = 0;
//文件上传地址
String filePath = getServletContext().getRealPath("/")+"smartUpload";
//如果文件夹不存在 则创建这个文件夹
File file = new File(filePath);
if(!file.exists())
{
file.mkdir();
}
//初始化对象
SmartUpload su = new SmartUpload();
su.initialize(getServletConfig(),request,response);
//设置文件最大容量
su.setMaxFileSize(10*1024*1024);
//设置所有文件最大容量
su.setTotalMaxFileSize(100*1024*1024);
//设置上传文件类型
su.setAllowedFilesList("rar,txt,jpg,bmp,gif");
try {
//设置禁止上传的文件类型
su.setDeniedFilesList("jsp,js,html,css");
//上传文件
su.upload();
System.out.println("userName=" + su.getRequest().getParameter("userName"));
count = su.save(filePath);
} catch (SQLException e) {
e.printStackTrace();
} catch (SmartUploadException e) {
e.printStackTrace();
}
for (int i = 0; i < su.getFiles().getCount(); i++) {
com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
System.out.println("-------------------------------------------------");
System.out.println("表单项名称:" + tempFile.getFieldName());
System.out.println("文件名:" + tempFile.getFileName());
System.out.println("文件长度:" + tempFile.getSize());
System.out.println("文件扩展名:" + tempFile.getFileExt());
System.out.println("文件全名:" + tempFile.getFilePathName());
System.out.println("-------------------------------------------------");
}
System.out.println("上传成功!共" + count + "个文件!");
}
在这个方法中需要注意的是,我们要拿表单上的其他元素的值,我们需要在su.upload()方法后去使用su.getRequest().getParameter("userName")来获得表单的值,不能使用request。throws ServletException, IOException {
//文件上传个数
int count = 0;
//文件上传地址
String filePath = getServletContext().getRealPath("/")+"smartUpload";
//如果文件夹不存在 则创建这个文件夹
File file = new File(filePath);
if(!file.exists())
{
file.mkdir();
}
//初始化对象
SmartUpload su = new SmartUpload();
su.initialize(getServletConfig(),request,response);
//设置文件最大容量
su.setMaxFileSize(10*1024*1024);
//设置所有文件最大容量
su.setTotalMaxFileSize(100*1024*1024);
//设置上传文件类型
su.setAllowedFilesList("rar,txt,jpg,bmp,gif");
try {
//设置禁止上传的文件类型
su.setDeniedFilesList("jsp,js,html,css");
//上传文件
su.upload();
System.out.println("userName=" + su.getRequest().getParameter("userName"));
count = su.save(filePath);
} catch (SQLException e) {
e.printStackTrace();
} catch (SmartUploadException e) {
e.printStackTrace();
}
for (int i = 0; i < su.getFiles().getCount(); i++) {
com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
System.out.println("-------------------------------------------------");
System.out.println("表单项名称:" + tempFile.getFieldName());
System.out.println("文件名:" + tempFile.getFileName());
System.out.println("文件长度:" + tempFile.getSize());
System.out.println("文件扩展名:" + tempFile.getFileExt());
System.out.println("文件全名:" + tempFile.getFilePathName());
System.out.println("-------------------------------------------------");
}
System.out.println("上传成功!共" + count + "个文件!");
}