JSP+Servlet
一、文件上传下载原理
在TCP/IP中,最早出现的文件上传机制是FTP。它是将文件由客户端发送到服务器的标准机制。但是在jsp编程中不能使用FTP方法来上传文件,这是由jsp的运行机制所决定的。
通过为表单元素设置Method=“post” enctype="multipart/form-data"属性,让表单提交的数据以二进制编码的方式提交,在接收此请求的Servlet中用二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传。
二、enctype属性的选择值范围
1、application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成url编码方式。
2、multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定的文件内容也封装到请求参数里。
3、text/plain:这种方式主要适用于直接通过表单发送邮件的方式。
代码内容
1.将文件读取到服务器指定目录下
2.获取文件内容的起止位置,和文件名称
3.将文件保存到项目的指定目录下
- <span style="font-size:18px;">public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- //从request中获取输入流信息
- InputStream fileSource = request.getInputStream();
- //创建存储在服务器的路径信息
- String tempFileName = "H:/tempFile";
- //指向临时文件
- File tempFile = new File(tempFileName);
- //outPutStream输出流指向临时文件
- FileOutputStream outputStream = new FileOutputStream(tempFile);
- //每次读取文件字节
- byte b[] = new byte[1024];
- int n;
- while((n=fileSource.read(b))!=-1){
- outputStream.write(b,0,n);
- }
- //关闭输出输入流
- fileSource.close();
- outputStream.close();
- //获取上传文件的名称
- RandomAccessFile randomFile = new RandomAccessFile(tempFile, "r");
- randomFile.readLine(); //获取第一行数据(对我们来说没有意义)
- String str = randomFile.readLine(); //获取第二行数据,内容为:Content-Disposition: form-data; name="myfile"; filename="C:\Users\lihf\Desktop\hello.txt"
- int beginIndex = str.lastIndexOf("\\")+1;
- int endIndex = str.lastIndexOf("\"");
- String fileName = str.substring(beginIndex, endIndex);
- //重新定位文件指针到头文件
- randomFile.seek(0);
- long startPosition=0;
- int i=1;
- //获取文件内容开始位置
- while((n=randomFile.readByte())!=-1&&i<=4){
- if(n=='\n'){
- startPosition = randomFile.getFilePointer();
- i++;
- }
- }
- startPosition = randomFile.getFilePointer() -1;
- //获取文件结束位置
- randomFile.seek(randomFile.length()); //文件指针定位到文件末尾
- long endPosition = randomFile.getFilePointer();
- int j=1;
- while(endPosition>=0&&j<=2){
- endPosition--;
- randomFile.seek(endPosition);
- if(randomFile.readByte()=='\n'){
- j++;
- }
- }
- endPosition = endPosition -1;
- //设置保存文件上传的路径
- String realPath = getServletContext().getRealPath("/")+"images";
- System.out.println("保存文件上传的路径:"+realPath);
- File fileupload = new File(realPath);
- if(!fileupload.exists()){
- fileupload.mkdir(); //创建此抽象路径名指定的目录。
- }
- File saveFile = new File(realPath, fileName);
- RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
- //从临时文件中读取文件内容(根据文件起止位置获取)
- randomFile.seek(startPosition);
- while(startPosition<endPosition){
- randomAccessFile.write(randomFile.readByte());
- startPosition = randomFile.getFilePointer();
- }
- //关闭输入输出流
- randomAccessFile.close();
- randomFile.close();
- tempFile.delete();
- request.setAttribute("result", "上传成功!");
- RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/01.jsp");
- dispatcher.forward(request, response);
- }</span>
三、文件下载原理
1、step1:需要通过HttpServletResponse.setContentType方法设置Content-type头字段的值,为浏览器无法使用某种方式或激活某个程序来处理的MIME类型,例如,“application/octet-stream”或“application/x-msdownload”等。
2、step2:需要通过HttpServletResponse.setHeader方法设置Content-Disposition头的值为“attachment;filename=文件名”。
3、step3:读取下载文件,调用HttpServletResponse.getOutputStream方法返回的OutputStream对象来向客户端写入附件文件内容。
- <span style="font-size:18px;">public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- //获取文件下载路径
- String path = getServletContext().getRealPath("/") + "images/";
- String filename = request.getParameter("filename");
- File file = new File(path + filename);
- if(file.exists()){
- //设置相应类型application/octet-stream
- response.setContentType("application/x-msdownload");
- //设置头信息
- response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
- InputStream inputStream = new FileInputStream(file);
- ServletOutputStream ouputStream = response.getOutputStream();
- byte b[] = new byte[1024];
- int n ;
- while((n = inputStream.read(b)) != -1){
- ouputStream.write(b,0,n);
- }
- //关闭流、释放资源
- ouputStream.close();
- inputStream.close();
- }else{
- request.setAttribute("errorResult", "文件不存在下载失败!");
- RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/01.jsp");
- dispatcher.forward(request, response);
- }
- }</span>
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP '01.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <link rel="stylesheet" type="text/css" href="css/common.css" />
- <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
- <script type="text/javascript">
- $(function(){
- $(".thumbs a").click(function(){
- var largePath=$(this).attr("href");
- var largeAlt=$(this).attr("title");
- $("#largeImg").attr({
- src:largePath,
- alt:largeAlt
- });
- return false;
- });
- $("#myfile").change(function(){
- $("previewImg").attr("src","file:///"+$("#myfile").val());
- });
- var la = $("#large");
- la.hide();
- $("#previewImg").mousemove(function(e){
- la.css({
- top:e.pagey,
- left:e.pagex
- }).html('<img src="'+this.src+'" />');
- }).mouseout(function(){
- la.hide();
- });
- });
- /* function showPreview(obj){
- var str = obj.value;
- document.getElementById("previewImg").innerHTML=
- "<img src='"+str+"'/>";
- alert(document.getElementById("previewImg").innerHTML);
- } */
- </script>
- </head>
- <body>
- <img id="previewImg" src="images/preview.jpg" width="80" height="80" />
- <form action="uploadServlet.do" method="post" enctype="multipart/form-data">
- 请选择上传图片:<input type="file" id="myfile" name="myfile" onchange="showPreview(this)" />
- <input type="submit" value="提交"/>
- </form>
- 下载<a href="downloadServlet.do?filename=hello.txt">hello.txt</a> ${errorResult}
- <div id="large"></div>
- <!-- <form action="">
- 请选择上传图片:<input type="file" id="myfile" name="myfile" onchange="showPreview(this)" />
- <div id="previewImg"></div>
- </form> -->
- <hr>
- <h2>图片预览</h2>
- <p><img id="largeImg" src="images/img1-lg.jpg" alt="Large Image"/></p>
- <p class="thumbs">
- <a href="images/img2-lg.jpg" title="Image2"><img src="images/img2-thumb.jpg"></a>
- <a href="images/img3-lg.jpg" title="Image3"><img src="images/img3-thumb.jpg"></a>
- <a href="images/img4-lg.jpg" title="Image4"><img src="images/img4-thumb.jpg"></a>
- <a href="images/img5-lg.jpg" title="Image5"><img src="images/img5-thumb.jpg"></a>
- <a href="images/img6-lg.jpg" title="Image6"><img src="images/img6-thumb.jpg"></a>
- </p>
- </body>
- </html>
使用非常简单,直接引入SmartUpload的jar文件就可以啦
- <span style="font-size:18px;">public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- //设置上传文件保存路径
- String filePath = getServletContext().getRealPath("/")+"images";
- File file = new File(filePath);
- if(!file.exists()){
- file.mkdir();
- }
- SmartUpload su = new SmartUpload();
- //初始化smartUpload
- su.initialize(getServletConfig(), request, response);
- //设置上传文件大小
- su.setMaxFileSize(1024*1024*10);
- //设置所有文件的大小
- su.setTotalMaxFileSize(102481024*100);
- //设置允许上传文件的类型
- su.setAllowedFilesList("txt,jpg,gif");
- String result = "上传能成功";
- try {
- //设置禁止上传文件类型
- su.setDeniedFilesList("jsp,rar");
- su.upload();
- int count = su.save(filePath);
- System.out.println("上传成功"+count+"文件!");
- } catch (Exception e) {
- result="上传文件失败!";
- <span style="white-space:pre"> </span>if(e.getMessage().indexOf("1015")!=-1){<span style="white-space:pre"> </span>
- <span style="white-space:pre"> </span>result = "上传文件失败:上传文件类型不正确!";
- <span style="white-space:pre"> </span>}else if(e.getMessage().indexOf("1010")!=-1){
- <span style="white-space:pre"> </span>result = "上传文件失败:上传文件类型不正确!";
- <span style="white-space:pre"> </span>}else if(e.getMessage().indexOf("1105")!=-1){
- <span style="white-space:pre"> </span>result = "上传文件失败:上传文件大小大于允许上传的最大值!";
- <span style="white-space:pre"> </span>}else if(e.getMessage().indexOf("1110")!=-1){
- <span style="white-space:pre"> </span>result = "上传文件失败:上传文件的总大小大于我们允许上传总大小的最大值!";
- <span style="white-space:pre"> </span>}
- <span style="white-space:pre"> </span>e.printStackTrace();
- }
- for(int i=0;i<su.getFiles().getCount();i++){
- <span style="white-space:pre"> </span>com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);
- <span style="white-space:pre"> </span>System.out.println("表单当中name属性值:"+tempFile.getFieldName());
- <span style="white-space:pre"> </span>System.out.println("上传文件名:"+tempFile.getFileName());
- <span style="white-space:pre"> </span>System.out.println("上传文件的大小:"+tempFile.getSize());
- <span style="white-space:pre"> </span>System.out.println("上传文件名拓展名:"+tempFile.getFileExt());
- <span style="white-space:pre"> </span>System.out.println("上传文件的全名:"+tempFile.getFilePathName());
- <span style="white-space:pre"> </span>}
- request.setAttribute("result",result);
- request.getRequestDispatcher("jsp/02.jsp").forward(request, response);
- }</span>
- <span style="font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP '02.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <link rel="stylesheet" type="text/css" href="css/common.css" />
- <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
- <script type="text/javascript">
- $(function(){
- $(".thumbs a").click(function(){
- var largePath=$(this).attr("href");
- var largeAlt=$(this).attr("title");
- $("#largeImg").attr({
- src:largePath,
- alt:largeAlt
- });
- return false;
- });
- });
- </script>
- </head>
- <body>
- <form action="smartUploadServlet.do" method="post" enctype="multipart/form-data">
- 上传文件1:<input type="file" name="myfile1"/><br>
- 上传文件2:<input type="file" name="myfile2"/><br>
- 上传文件3:<input type="file" name="myfile3"/><br>
- <input type="submit" value="提交"> ${result}
- </form>
- <hr></span>
- <span style="font-size:18px;"> 下载:<a href="smartDownloadServlet.do?filename=img5-lg.jpg">img5-lg.jpg</a>
- <hr>
- <h2>图片预览</h2>
- <p><img id="largeImg" src="images/img1-lg.jpg" alt="Large Image"/></p>
- <p class="thumbs">
- <a href="images/img2-lg.jpg" title="Image2"><img src="images/img2-thumb.jpg"></a>
- <a href="images/img3-lg.jpg" title="Image3"><img src="images/img3-thumb.jpg"></a>
- <a href="images/img4-lg.jpg" title="Image4"><img src="images/img4-thumb.jpg"></a>
- <a href="images/img5-lg.jpg" title="Image5"><img src="images/img5-thumb.jpg"></a>
- <a href="images/img6-lg.jpg" title="Image6"><img src="images/img6-thumb.jpg"></a>
- </p>
- </body>
- </html></span>
- <span style="font-size:18px;"><span style="background-color: rgb(255, 255, 255);">下载部分的代码</span></span>
- <span style="font-size:18px;">public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String filename = request.getParameter("filename");
- SmartUpload su = new SmartUpload();
- su.initialize(getServletConfig(), request, response);
- su.setContentDisposition(null);
- try {
- su.downloadFile("/images/"+filename);
- } catch (SmartUploadException e) {
- e.printStackTrace();
- }
- }</span>
Struts2实现上传下载:
上传jsp页面代码:
- <span style="font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP '03.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <link rel="stylesheet" type="text/css" href="css/common.css" />
- <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
- <script type="text/javascript">
- $(function(){
- $(".thumbs a").click(function(){
- var largePath=$(this).attr("href");
- var largeAlt=$(this).attr("title");
- $("#largeImg").attr({
- src:largePath,
- alt:largeAlt
- });
- return false;
- });
- });
- </script>
- </head>
- <body>
- <h2> 文件上传</h2>
- <form action="upload.action" method="post" enctype="multipart/form-data">
- 上传文件1:<input type="file" name="upload"/><br>
- 上传文件2:<input type="file" name="upload"/><br>
- 上传文件3:<input type="file" name="upload"/><br>
- <input type="submit" value="提交"> ${result}
- </form>
- <hr>
- <h2>图片预览</h2>
- <p><img id="largeImg" src="images/img1-lg.jpg" alt="Large Image"/></p>
- <p class="thumbs">
- <a href="images/img2-lg.jpg" title="Image2"><img src="images/img2-thumb.jpg"></a>
- <a href="images/img3-lg.jpg" title="Image3"><img src="images/img3-thumb.jpg"></a>
- <a href="images/img4-lg.jpg" title="Image4"><img src="images/img4-thumb.jpg"></a>
- <a href="images/img5-lg.jpg" title="Image5"><img src="images/img5-thumb.jpg"></a>
- <a href="images/img6-lg.jpg" title="Image6"><img src="images/img6-thumb.jpg"></a>
- </p>
- </body>
- </html></span>
- <span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
- "http://struts.apache.org/dtds/struts-2.3.dtd">
- <struts>
- <constant name="struts.enable.DynamicMethodInvocation" value="false" />
- <constant name="struts.devMode" value="true" />
- <!-- 国际化 -->
- <constant name="struts.custom.i18n.resources" value="app"></constant>
- <package name="default" namespace="/" extends="struts-default">
- <action name="upload" class="com.lihf.action.FileUploadAction">
- <result>/jsp/03.jsp</result>
- <result name="input">/jsp/error.jsp</result>
- <!-- 配置拦截器限制上传文件类型及大小 -->
- <interceptor-ref name="fileUpload">
- <param name="allowedTypes">image/bmp,image/x-png,image/gif,image/pjpeg</param>
- <param name="maximumSize">2M</param>
- </interceptor-ref>
- <interceptor-ref name="defaultStack"></interceptor-ref>
- </action>
- <action name="download" class="com.lihf.action.DownLoadAction">
- <param name="inputPath">/images/img2-lg.jpg</param>
- <result name="success" type="stream">
- <param name="contentType">application/octet-stream</param>
- <param name="inputName">inputStream</param>
- <!-- 以附件的形式下载 -->
- <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
- <param name="bufferSize">8192</param>
- </result>
- </action>
- </package>
- </struts></span>
- <span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
- <display-name>scxz</display-name>
- <servlet>
- <servlet-name>UploadServlet</servlet-name>
- <servlet-class>com.lihf.servlet.UploadServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>DownloadServlet</servlet-name>
- <servlet-class>com.lihf.servlet.DownloadServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>SmartUploadServlet</servlet-name>
- <servlet-class>com.lihf.servlet.SmartUploadServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>SmartDownloadServlet</servlet-name>
- <servlet-class>com.lihf.servlet.SmartDownloadServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>UploadServlet</servlet-name>
- <url-pattern>/uploadServlet.do</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>DownloadServlet</servlet-name>
- <url-pattern>/downloadServlet.do</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>SmartUploadServlet</servlet-name>
- <url-pattern>/smartUploadServlet.do</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>SmartDownloadServlet</servlet-name>
- <url-pattern>/smartDownloadServlet.do</url-pattern>
- </servlet-mapping>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app></span>
- <span style="font-size:18px;">package com.lihf.action;
- import java.io.File;
- import java.util.List;
- import org.apache.commons.io.FileUtils;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- public class FileUploadAction extends ActionSupport {
- private List<File> upload;
- private List<String> uploadContentType;
- private List<String> uploadFileName;
- private String result;
- public List<File> getUpload() {
- return upload;
- }
- public void setUpload(List<File> upload) {
- this.upload = upload;
- }
- public List<String> getUploadContentType() {
- return uploadContentType;
- }
- public void setUploadContentType(List<String> uploadContentType) {
- this.uploadContentType = uploadContentType;
- }
- public List<String> getUploadFileName() {
- return uploadFileName;
- }
- public void setUploadFileName(List<String> uploadFileName) {
- this.uploadFileName = uploadFileName;
- }
- public String getResult() {
- return result;
- }
- public void setResult(String result) {
- this.result = result;
- }
- @Override
- public String execute() throws Exception {
- String path = ServletActionContext.getServletContext().getRealPath("/images");
- File file = new File(path);
- if(!file.exists()){
- file.mkdir();
- }
- for(int i=0;i<upload.size();i++){
- FileUtils.copyFile(upload.get(i), new File(file,uploadFileName.get(i)));
- }
- result ="上传成功!";
- return SUCCESS;
- }
- }
- </span>
action方法:
- <span style="font-size:18px;">package com.lihf.action;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.URLEncoder;
- import org.apache.commons.io.FileUtils;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- public class DownLoadAction extends ActionSupport {
- public String inputPath;
- public String fileName;
- public String getFileName() {
- return fileName;
- }
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
- public String getInputPath() {
- return inputPath;
- }
- public void setInputPath(String inputPath) {
- this.inputPath = inputPath;
- }
- @Override
- public String execute() throws Exception {
- return SUCCESS;
- }
- public InputStream getInputStream() throws IOException{
- String path = ServletActionContext.getServletContext().getRealPath("/images");
- String filePath = path+"\\"+fileName;
- File file = new File(filePath);
- return FileUtils.openInputStream(file);
- //根据文件路径获取流信息固定下载文件使用方法
- //return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
- }
- public String getDownloadFileName(){
- //如果是中文的文件名称需要转码
- String downloadFileName = "";
- try {
- downloadFileName = URLEncoder.encode("文件下载.jpg","UTF-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return downloadFileName;
- }
- }
- </span>
<a href="download.action?fileName=img3-lg.jpg">文件下载(图片)</a>