文件上传原理
表单method属性应该设置为POST方法,不能使用GET方法。
表单enctype属性应该设置为multipart/form-data.
表单action属性应该设置为在后端服务器上处理文件上传的Servlet文件。下面的实例使用了UploadServletServlet来上传文件。
上传单个文件,您应该使用单个带有属性type="file"的<input.../>标签。为了允许多个文件上传,请包含多个name属性值不同的input标签。输入标签具有不同的名称属性的值。浏览器会为每个input标签关联一个浏览按钮
需要jar包
定义form
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<style type = "text/css">
table{
width:100%;
border:1px solid black;
text-align:center;
}
th,td{
border:1px solid black;
}
</style>
<body>
<!-- 上传文文件 需要表单enctype属性应该设置为 enctype="multipart/form-data" -->
<form action="${pageContext.request.contextPath}/us" method="post" enctype="multipart/form-data">
<input type = "file" name = "myFile" size="50"/>
<input type = "submit" value="上传文件"/>
</form>
<table>
<tr>
<th>文件名</th>
<th>下载</th>
</tr>
<c:forEach var="item" items="${requestScope.list}">
<tr>
<td>${item.name}</td>
<td><a href='ds?fileName=${item.name}'>下载</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
文件上传
package cn.et.upload;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* 文件上传
*/
public class UpaloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String contextPath = request.getContextPath();//获取上下文路径
PrintWriter out = response.getWriter();
//接收文件
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//判断是否是文件上传请求
if(isMultipart){
//用于创建解析文件上传的工厂类
DiskFileItemFactory factory = new DiskFileItemFactory();
//默认上传文件 暂时存放在临时目录 System.getProperty("java.io.tmpdir");
//也有可能是tomcat/temp目录
//用于从请求中解析文件
ServletFileUpload upload = new ServletFileUpload(factory);
//设置字符集 解决文件名中文乱码问题
upload.setHeaderEncoding("UTF-8");
try {
//解析出文件的个数
List<FileItem> list = upload.parseRequest(request);
for(FileItem li:list){
//表示输入的文本框
if(li.isFormField()){
System.out.println(li.getFieldName()+"=>"+li.getString());
}else{//表示输入的是文件
//获取文件名
String fileName=li.getName();
InputStream is = li.getInputStream();
String destPath = "F:/file/"+fileName;
FileOutputStream fis = new FileOutputStream(destPath);
byte[] bt = new byte[1024];
int len = 0;
while((len=is.read(bt))!=-1){
fis.write(bt,0,len);
}
fis.close();
is.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}finally{
response.sendRedirect(contextPath+"/sud");
}
}
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
文件下载
package cn.et.download;
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;
/**
* 文件下载
*/
public class DewnloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
//文件下载的输出流
OutputStream os = response.getOutputStream();
//获取传递过的的文件名
String fileName = request.getParameter("fileName");
//告诉浏览器下载的文件名
response.setHeader("Location", URLEncoder.encode(fileName,"UTF-8"));
response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(fileName,"UTF-8"));
//将文件流 写入OutputSteam
FileInputStream fis = new FileInputStream("F:/file"+"/"+fileName);
byte[] bys = new byte[1024];
int len = 0;
while((len=fis.read(bys))!=-1){
os.write(bys, 0, len);
os.flush();
}
os.close();
fis.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
}
将文件夹里的文件获取出来,将显示在浏览器上
package cn.et.show;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowUploadDownload extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
File file = new File("F:/file");
File[] files = file.listFiles();
//设置样式
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
for(File tfile:files){
Map<String, String> map = new HashMap<String, String>();
String name = tfile.getName();
map.put("name", name);
list.add(map);
}
request.setAttribute("list", list);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
示例:
访问ShowUploadDownload,将文件夹里的文件显示在浏览器上
上传文件
下载文件 点击下载