9-文件上传和下载

apache commons类库jar包

一。文件上传
1.导入jar文件:commons-fileupload1.3.3.jar,commons-io.2.5.jar
2.页面:
  <form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="files"><br>
    <input type="text" name="miaoshu"><br>
    <input type="submit" value="提交">
  </form>
注意:form的method必须为post,form必须要有enctype="multipart/form-data"
    input type=“file” 必须要有name属性,名字可以自定义
3.后台程序部分:
4.要在项目中创建一个文件夹来存放上传后的文件,在webcontent目录下创建upload
5.上传后的文件的路径,位于
  D:\javaTools\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\StudentManager\upload

 

 实例1:

  upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="upload" method="post" enctype="multipart/form-data">
        <input type="file" name="files"><br>
        <input type="text" name="miaoshu"><br>
        <input type="submit" value="提交"> 
    </form>
</body>
${mess}
</html>
FileupLoadServlet.java
package com.control;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/upload")
public class FileupLoadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //创建一个请求解析工厂
            FileItemFactory factory = new DiskFileItemFactory();
            //根据解析工厂创建一个文件上传对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            //设置上传文件的总大小 4m
            upload.setSizeMax(4194304);
            //上传对象去解析请求,将请求中的所有表单元素全部打包成一个集合,文件和非文件都会打包进来
            List<FileItem> files = upload.parseRequest(req);
            //获取项目中文件夹的绝对路径,用来存放上传的文件
            String realPath = getServletContext().getRealPath("upload");
            
            if(files!=null){
                for (FileItem fi : files) {
                    //fi.isFormField()判断该参数是不是一个普通的表单元素
                    if(fi.isFormField()){//是一个普通元素
                        //解决中文乱码问题
                        //fi.getFieldName() 获取表单的元素名
                        //fi.getString() 获取表单元素的值
                        System.out.println("name="+fi.getFieldName()+",value="+new String(fi.getString().getBytes("iso-8859-1"),"utf-8"));
                    }else{//是一个文件
                        //构造客户端完整路径的文件对象,目的是为了获取该文件的文件名
                        File fullFile = new File(fi.getName());
                        //根据服务器的路径和文件名老构造要保存到服务器的文件对象
                        File savedFile = new File(realPath, fullFile.getName());
                        //将文件写入
                        fi.write(savedFile);
                    }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        req.setAttribute("mess", "<script>alert('上传成功!')</script>");
        req.getRequestDispatcher("upload.jsp").forward(req, resp);
    }
}

实例2:

  load.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="down">下载</a>
</body>
</html>

  FileDownLoadServlet.java

package com.control;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/down")
public class FileDownLoadServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求  
        //读取要下载的文件  
        File f = new File("d:/JavaEE课程体系.xlsx");  
        if(f.exists()){  
            FileInputStream  fis = new FileInputStream(f);  
            String filename=URLEncoder.encode(f.getName(),"utf-8"); //解决中文文件名下载后乱码的问题  
            byte[] b = new byte[fis.available()];  
            fis.read(b);  
            resp.setCharacterEncoding("utf-8");  
            resp.setHeader("Content-Disposition","attachment; filename="+filename+"");  
            //获取响应报文输出流对象  
            ServletOutputStream  out =resp.getOutputStream();  
            //输出  
            out.write(b);  
            out.flush();  
            out.close();  
        }     
    }
}

 

posted @ 2019-04-21 15:24  五柳先生柳三变  阅读(164)  评论(0编辑  收藏  举报