文件的上传与下载,有三个前提:关于表单的type属性为File 其提交方式为post enctype="multipart/form-data " 多部件上传
关于文件格式及大小的限制的JS代码如下所示:
<script type="text/javascript">
function fileChange(target) {
//检测上传文件的类型
var imgName = document.all.up_file.value;
var ext, idx;
if(imgName == '') {
document.all.submit_upload.disabled = true;
alert("请选择需要上传的文件!");
return;
} else {
idx = imgName.lastIndexOf(".");
if(idx != -1) {
ext = imgName.substr(idx + 1).toUpperCase();
ext = ext.toLowerCase();
// alert("ext="+ext);
if(ext != 'zip' && ext != 'rar') {
document.all.submit_upload.disabled = true;
alert("只能上传.zip .rar 类型的文件!");
return;
}
} else {
document.all.submit_upload.disabled = true;
alert("只能上传.zip .rar 类型的文件!");
return;
}
}
//检测上传文件的大小
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
var fileSize = 0;
if(isIE && !target.files) {
var filePath = target.value;
var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
var file = fileSystem.GetFile(filePath);
fileSize = file.Size;
} else {
fileSize = target.files[0].size;
}
var size = fileSize / 1024 * 1024;
if(size > (10*1024*1024)) {
document.all.submit_upload.disabled = true;
alert("文件大小不能超过10M");
} else {
document.all.submit_upload.disabled = false;
}
}
</script>
下面部分为servlet中的代码,其代码如下
package com.itqf.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
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.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
public class DealServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//浏览器 -- 服务器 --> 本地磁盘
//1.判断类型
boolean is = ServletFileUpload.isMultipartContent(request);
if (is) {
//2.创建本地磁盘工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
File file = new File("c:\\workspace");
//设置缓存路径
factory.setRepository(file);
//3.创建解析核心类
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener() {
@Override
public void update(long arg0, long arg1, int arg2) {
// TODO Auto-generated method stub
System.out.println(arg0+" -- "+arg1+" -- "+arg2);
}
});
//解决上传中文文件名乱码问题
upload.setHeaderEncoding("UTF-8");
// upload.setFileSizeMax(); //限制单个input 的大小
// upload.setSizeMax(1024*1024*10); //限制表单中文件的总大小 1024*1024*1024 GB
//在正常情况下,在HTML中利用JS设置上传文件格式及大小的限制
//4.解析请求
try {
List<FileItem> items = upload.parseRequest(request);
//FileItem就是每一个input
//普通的文本input 还有一个 文件 input
for (FileItem fileItem : items) {
if (fileItem.isFormField()) {
//ture 普通的文本
//name value
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
System.out.println(name+" --- "+ value);
}else{
//文件
dealFile(fileItem);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 处理文件input的
* @param fileItem
*/
private void dealFile(FileItem fileItem) {
//1.获取文件的名字
String filename = fileItem.getName();
if (filename != null) {
filename = FilenameUtils.getName(filename);
//c://xx/xx/i.jpg = i.jpg 0
//filename= filename.substring(filename.lastIndexOf(File.separator)+1);
}
//2.文件保存的位置
//1. 指定磁盘
//2. 保存本项目下
ServletContext servletContext = getServletContext();
//获取时间
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
String time = format.format(new Date());
//根据相对路径获取绝对路径
String path = servletContext.getRealPath("/WEB-INF/filedir/"+time);
System.out.println("文件夹的路径:"+path);
//创建保存的文件夹
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs(); //创建文件夹
}
//保证文件不重复
filename = UUID.randomUUID()+filename;
// filename = System.currentTimeMillis()+filename;
//创建具体的文件
File file = new File(dir,filename);
try {
//写到指定的文件中
// fileItem.write(file);
write(fileItem);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void write(FileItem fileItem) throws IOException{
String filename = fileItem.getName();
ServletContext servletContext = getServletContext();
//获取时间
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
String time = format.format(new Date());
//根据相对路径获取绝对路径
String path = servletContext.getRealPath("/WEB-INF/filedir/"+time);
System.out.println("文件夹的路径:"+path);
//创建保存的文件夹
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs(); //创建文件夹
}
//保证文件不重复
filename = UUID.randomUUID()+filename;
// filename = System.currentTimeMillis()+filename;
//创建具体的文件
File file = new File(dir,filename);
//得到文件内容的流
InputStream inputStream = fileItem.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte [] buffer = new byte[1024];
int len = -1;
while((len = inputStream.read(buffer))!=-1){
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();
inputStream.close();
fileItem.delete();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}