jsp/servlet实现文件上传下载

文件上传

(1)下载相关 jar包,配置好web.xml中各种映射。

(2)jsp页面,注意form提交类型:

<form id="" name="" method="post" action="DBServlet?operate=adddb" enctype="multipart/form-data">
      数据文件上传:<input size='100' id="wenjian" name="wenjian" type="file" />
</form>

(3)servlet:

数据库里有一个字段用来存在新的文件名字,而文件保存在服务器的某个目录下头。

String picpath = this.getServletContext().getRealPath("/");
//参考:http://blog.sina.com.cn/s/blog_639dde240100mzvj.html
//E:workspaceweb应用名
String saveDirectory = picpath + "UserFiles/DBfile";
// 每个文件最大2G,最多3个文件,所以...
int maxPostSize = 1024 * 1024 * 1024;
MultipartRequest multi = new MultipartRequest(request, saveDirectory,maxPostSize, "utf-8");
String fileType = null;
String fileName = null;
String newFileName = null;
String[] cid = multi.getParameterValues("cid");//页面某个name属性,有固定value,为了给文件重命名时区分是哪里上传的。
Enumeration files = multi.getFileNames();//枚举
String elementname = null;
File file = null;
int i = 1;
while (files.hasMoreElements()) {
	elementname = (String) files.nextElement();
	file = multi.getFile(elementname);
	if (file != null) {
		fileName = file.getName();
		fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
		String extName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
		newFileName = format.format(date) + "_"+ cid[cid.length - i] + "." + extName;
		renameFile(saveDirectory, fileName, newFileName);
	}
	i++;
}
文件下载

(1)下载jsp页面:

UserFiles/DBfile是服务器上文件夹,而dbpath是数据库里存储该对象文件名字段。

<a href="download.jsp?path=<%=getServletContext().getRealPath("/") %>/UserFiles/DBfile/<%=dbpath%>"><%=dbpath %></a>

 (2)download.jsp页面,一个servlet而已,只是处理下载,jsp全部代码:

<%@ page contentType="text/html;charset=gb2312" 
import="com.jsl.message.util.SmartUpload.*" %><%
String path=request.getParameter("path");
//新建一个SmartUpload对象 
SmartUpload su = new SmartUpload(); 
//初始化 
su.initialize(pageContext); 
//设定contentDisposition为null以禁止浏览器自动打开文件, 
//保证点击链接后是下载文件。若不设定,则下载的文件扩展名为 
//doc时,浏览器将自动用word打开它。扩展名为pdf时, 浏览器将用acrobat打开。 
su.setContentDisposition(null);
System.out.print("____"+path);
// 下载文件 
//su.downloadFile("/attch/materiallist/文档.doc");
su.downloadFile(path,request); 
%>
原文地址:https://www.cnblogs.com/sunyt/p/4355655.html