上传界面必须要使用jsp文件,我之前想过使用input标签中的file来获取文件的位置,但是很无奈,每次文件存储到数据库中都是一个C:fakepath:…的文件。看了很多文章,了解到这是因为浏览器的保护机制。最后也没想到什么好的解决办法。所以现在使用JSP来上传文件和下载文件,此篇文章用于记录。
首先:表单要设计成这个样子:
<form action ="${pageContext.request.contextPath}/file/add" method = "post" enctype="multipart/form-data">
用户名:<input type="text" name = "username"/><br>
简历:<input type="file" name = "photo"/><font color = "red">只支持上传word文件!!!!其他文件格式不对呦</font>
<br>
<input type="submit" value ="提交"/><font color = "red">最大支持5MB</font>
</form>
简单解释一下吧pageCotext是当前作用域对象,request是获取它的请求头,contextPath就是文件的名字地址啥的,后面的/file/add是将这个参数转交给FileAddServlet这个servlet来处理,
enctype="multipart/form-data表明上传的是一个文件
接下来是Servlet中post方法的代码,注释很详细,有什么不懂的请看注释吧:
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset =utf-8");
//获取用户名名
//通过全局变量获取username
ServletContext application = request.getServletContext();
Object obj = application.getAttribute("username");
PrintWriter out = null;
out = response.getWriter();
if(obj == null){
out.print("<script type = 'text/javascript'>");
out.print("alert('请先使用求职人员登录才能上传简历!!!!!!!!!')");
out.print("</script>");
out.print("<a href= 'http://localhost:8080/myweb/login.html'>" +
"<button>点我返回登录界面</button>" +
"</a>");
return;
}
String username = (String)obj;
FileDao dao = new FileDao();
int result = 0;
//1.判断他是不是multpart请求
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
throw new RuntimeException("当前请求不支持文件上传");
}
//2.创建一个fileItems工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置临时文件的边界值,大于该值上传文件会先保存在临时文件中,否则,上传文件将直接写入到内存
//单位:字节
factory.setSizeThreshold(1024*1024*5);
//设置临时文件
String tempPath = this.getServletContext().getRealPath("/temp");
File temp = new File(tempPath);
factory.setRepository(temp);
//设置编码
/*
还有另一种方式
upload.setHeaderEncoding("utf-8");
设置每一个item的头部编码,可以解决文件名的中文乱码问题
*/
//创建一个文件上传核心组件
ServletFileUpload upload = new ServletFileUpload(factory);
//设置单个文件上传的最大边界值
upload.setFileSizeMax(1024*1024*5);
//设置一次上传所有文件的总和最大值为(主要用于上传多个文件时起作用)
upload.setSizeMax(1024*1024*10);
//解析请求,获取到所以的item
List<FileItem> items = upload.parseRequest(request);
//遍历item
for (FileItem item : items) {
if(item.isFormField()){
//如果item是普通表单项目
String fieldName = item.getFieldName(); //获取表单项名称
String filedValue = item.getString("utf-8"); //获取表单项的值
System.out.println(fieldName + filedValue);
System.out.println(fieldName + filedValue);
}else {
//若item是文件表单项目
String fileName = item.getName();//获取上传文件的原始名称
if(fileName == ""){
out.print("<script type = 'text/javascript'>");
out.print("alert('必须要选择文件才能上传!!!!!!!!!')");
out.print("</script>");
out.print("<a href= 'http://localhost:8080/myweb/upload.jsp'>" +
"<button>点我返回上传文件界面</button>" +
"</a>");
return;
}
fileName = System.currentTimeMillis()+fileName;//给原来的名字加上个系统时间,就不会被删除
// (解决同名被删除问题)
//获取输入流,其中有上传文件的内容
InputStream is = item.getInputStream();
//获取文件保存在服务器的路径
String path = this.getServletContext().getRealPath("/File");
//获取当前的系统时间
Date date = new Date();
//格式化日期为指定日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String now = sdf.format(date);
path =path +"/" +now;
//若该目录不存在,则创建该目录
File dirFile = new File(path);
if(!dirFile.exists()){
dirFile.mkdir();
}
//创建目标文件将来用于保存
File descfile = new File(path,fileName);
String address = path+"/"+fileName;
result = dao.add(username,address);
//创建文件输出流
OutputStream os = new FileOutputStream(descfile);
//将输入流中的数据写入到输出流中
int len = -1;
byte[] buffer = new byte[1024*1024*5];
while ((len = is.read(buffer)) != -1){
os.write(buffer,0,len);
}
//关闭流
os.close();
is.close();
//删除临时文件
item.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
if(result == 1){
out.print("<script type = 'text/javascript'>");
out.print("alert('会员"+username+"简历上传成功!!!!')");
out.print("</script>");
out.print("<a href= 'http://localhost:8080/myweb/index.html'>" +
"<button>点我返回主界面</button>" +
"</a>");
}else{
out.print("<script type = 'text/javascript'>");
out.print("alert('由于不可告人的原因,简历上传失败!!!!')");
out.print("alert('请联系管理员!!!!')");
out.print("</script>");
out.print("<a href= 'http://localhost:8080/myweb/upload.jsp'>" +
"<button>点我重新上传文件</button>" +
"</a>");
}
这样文件就能上传上去了,会保存在你创建的file文件夹中,接下来是下载功能
有两种方式,我的这个方式是从数据库中获取到需要下载的文件的地址
请看代码:
= String username = request.getParameter("username");
//根据用户名拿到简历的地址
DownloadDao dao =new DownloadDao();
String address = dao.find(username);//简历的存放地址
File file = new File(address);
//判断文件是否存在
if(file.exists()){
System.out.println(file.getName());//获取文件名
System.out.println(file.getParent());//获取文件父级路径
}
String[] doc = file.getName().split("\\.");
String str = doc[1];
//修改响应的头部属性content-disposition值为attachment
String filename = "简历."+str;
//解决乱码问题
//打散:按当前的字符编码进行打散
byte[] bytes = filename.getBytes("utf-8");
//组装:按照目标字符编码进行组装
filename = new String(bytes,"ISO8859-1");//W3C规定的,浏览器只能识别这个字节数据,而utf-8是字符型的
response.setHeader("content-disposition","attachment;filename = "+filename);
//获取连接服务端的输入流
FileInputStream is = new FileInputStream(file);
//获取输出流
ServletOutputStream os = response.getOutputStream();
//将输入流中的数据写入到输出流
int len = -1;
byte[] buffer = new byte[1024*1024*5];
while((len = is.read(buffer))!=-1){
os.write(buffer,0,len);
}
os.close();
is.close();
}
这样文件的上传和下载功能就实现了!