2011级-csdn-java-张侃— JDBC开发—文件的上传和下载(一)

感受 同时被 2 个专栏收录
60 篇文章 0 订阅
67 篇文章 0 订阅

private String id;

private String savename; //上传文件的名称,文件的uuid

private String realName; //上传文件的真实名称

private String savepath; //记住文件的位置

private Date uptime; //文件的上传时间

private String description; //文件的描述

private String username; //上传人

Tip:课程总结

通过本课程你应该熟练掌握了在web应用中集成apache commons fileupload组件上传多个文件。

在实际项目应用中,上传文件所引发的存储问题、安全性问题。

实现上传文件的下载

UploadServlet.java代码

package com.csdn.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.csdn.domain.Upfile;
import com.csdn.service.FileDaoService;
import com.csdn.utils.WebUtil;
public class UploadServlet extends HttpServlet {
/**
* 
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Upfile upfile = null;
try {
upfile = WebUtil.doFile(request, this.getServletContext()
.getRealPath("/WEB-INF/upload"), Upfile.class);
} catch (Exception e) {
request.setAttribute("message", "上传失败");
request.getRequestDispatcher("/message.jsp").forward(request,
response);
return;
}
try{
FileDaoService service = new FileDaoService();
service.add(upfile);
request.setAttribute("message", "上传成功");

}catch(Exception e){
request.setAttribute("message", "上传成功,保存数据失败");
}
request.getRequestDispatcher("/message.jsp").forward(request, response);

}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}


ListFileServlet.java代码

package com.csdn.web.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.csdn.domain.Upfile;
import com.csdn.service.FileDaoService;
public class ListFileServlet extends HttpServlet {
/**
* 
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
FileDaoService service = new FileDaoService();
List<Upfile> list = service.getAllFile();
request.setAttribute("list", list);
request.getRequestDispatcher("/listfile.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}


DownFileServlet.java代码


package com.csdn.web.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.csdn.domain.Upfile;
import com.csdn.service.FileDaoService;
public class DownFileServlet extends HttpServlet {
/**
* 
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
FileDaoService service = new FileDaoService();
Upfile upfile = service.findFile(id);
if(upfile==null){
request.setAttribute("message", "该资源已被删除了");
request.getRequestDispatcher("/message.jsp").forward(request, response);
return;
}
String savepath = upfile.getSavepath();
String uuidname = upfile.getUuidname();
String realname = upfile.getRealname();
File f = new File(savepath+"\\"+uuidname);

response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(realname,"UTF-8"));
FileInputStream in = new FileInputStream(f);
OutputStream out = response.getOutputStream();

byte[] buf = new byte[1024];
int len = 0;
while((len=in.read(buf))>0){
out.write(buf, 0, len);
}
in.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}


WebUtil.java代码

package com.csdn.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.csdn.domain.Upfile;
public class WebUtil {
@SuppressWarnings("unchecked")
public static <T> Upfile doFile(HttpServletRequest request,
String realPath, Class<T> clazz) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(request.getSession()
.getServletContext().getRealPath("/temp")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List<FileItem> list = upload.parseRequest(request);
Upfile upfile = (Upfile) clazz.newInstance();
for (FileItem item : list) {
if (item.isFormField()) {
String inputname = item.getFieldName();
String inputvalue = item.getString("UTF-8");
// System.out.println(inputname+"..."+inputvalue);
BeanUtils.setProperty(upfile, inputname, inputvalue);
} else {
String filename = item.getName();
String realname = filename.substring(filename
.lastIndexOf("\\") + 1);
upfile.setRealname(realname);
String uuidname = generateuuidName(realname);
upfile.setUuidname(uuidname);
String savepath = generateSavepath(realname, realPath);
upfile.setSavepath(savepath);
InputStream in = item.getInputStream();
FileOutputStream out = new FileOutputStream(savepath + "\\"
+ uuidname);
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
item.delete();
}
upfile.setId(UUID.randomUUID().toString());
upfile.setUptime(new Date());
}
return upfile;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private static String generateSavepath(String realname, String realPath) {
int dir1 = realname.hashCode() & 0xf;
int dir2 = (realname.hashCode() >> 4) & 0xf;
String savepath = realPath + "\\" + dir1 + "\\" + dir2;
File f = new File(savepath);
if (!f.exists()) {
f.mkdirs();
}
return savepath;
}
private static String generateuuidName(String realname) {
String ext = realname.substring(realname.lastIndexOf("."));
return UUID.randomUUID().toString() + ext;
}
}


upload.jsp代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>上传文件</title>
</head>
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<table align="center" border="1" width="80%">
<tr>
<td>
用户名:
</td>
<td>
<input type="text" name="username" />
</td>
</tr>
<tr>
<td>
文件:
</td>
<td>
<input type="file" name="file" />
</td>
</tr>
<tr>
<td>
文件描述:
</td>
<td>
<textarea name="description"></textarea>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="上传"></td>
</tr>
</table>
</form>
</body>
</html>


listfile.jsp代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>下载的资源列表</title>
</head>

<body>
<table border="1px" width="80%">
<tr>
<td>文件名</td>
<td>文件描述</td>
<td>上传时间</td>
<td>上传用户</td>
<td>操作</td>
</tr>
<c:forEach items="${list}" var="me">
<tr>
<td>${me.realname }</td>
<td>${me.description }</td>
<td>${me.uptime }</td>
<td>${me.username }</td>
<td><a href="DownFileServlet?id=${me.id }">下载</a>|<a href="DeleteFileServlet?id=${me.id }">删除</a></td>
</tr>

</c:forEach>

</table>
</body>
</html>


  • 1
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值