JavaWeb之文件上传

编程技术  /  houtizong 发布于 3年前   67
1.上传组件

①Apache的Commons FileUpload

②JavaZoom的UploadBean

③JspSmartUpload



2.下载Commons的FileUpload组件

地址:http://commons.apache.org/fileupload/

同时还要下载Commons的IO组件

地址:http://commons.apache.org/io/



3.使用实例

步骤一:创建文件上传的页面:fileUpload.jsp

注意表单的 enctype 属性,这个设置很重要,详情请见:http://www.cnblogs.com/yinger/archive/2011/09/11/2173689.html

<%@ 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="<%=request.getContextPath() %>/servlet/FileUploadServlet" method="post" enctype="multipart/form-data" >
        上传人名:<input type="text" name="name" /><br/>     
          上传文件:<input type="file" name="file" /><br/>
          <input type="submit" name="submit" value="提交" />
      </form>
  </body>
</html>

步骤二:创建处理文件上传的servlet:fileUploadServlet

package com.yinger.servlet;

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

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {
   
    private ServletContext sc;
    private String savePath;
    private static final long serialVersionUID = 151650843430214502L;

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

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       
        request.setCharacterEncoding("UTF-8");
   
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);//通过工厂生成一个处理文件上传的servlet对象
       
        try {
            List items = servletFileUpload.parseRequest(request);//解析request
            Iterator iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                if(item.isFormField()){//表单的参数字段
                    System.out.println("表单的参数名称:"+item.getFieldName()+",表单的参数值:"+item.getString("UTF-8"));
                }else {
                    if(item.getName()!=null && !item.getName().equals("")){//一个上传的文件
                        System.out.println("文件的名称:"+item.getName());
                        System.out.println("文件的大小:"+item.getSize());
                        System.out.println("文件的类型:"+item.getContentType());
                       
                        File tempFile = new File(item.getName());//getName得到的文件名称包含了它在客户端的路径
                        File file = new File(sc.getRealPath("/")+savePath,tempFile.getName());
                        item.write(file);//将上传的文件写入到file中
                       
                        request.setAttribute("message", "上传文件成功!");
                    }else{
                        request.setAttribute("message", "没有选择上传文件!");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", "上传文件失败!");
        }
       
        request.getRequestDispatcher("/fileUploadResult.jsp").forward(request, response);//转向,输出结果
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        savePath = config.getInitParameter("savePath");
        sc = config.getServletContext();       
    }
   
}

步骤三:修改web.xml

<?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_2_5.xsd" version="2.5">
  <display-name></display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>FileUploadServlet</servlet-name>
    <servlet-class>com.yinger.servlet.FileUploadServlet</servlet-class>
    <init-param> <!-- Servlet的初始化参数,配置上传文件的保存路径,这里是当前应用的uplods目录下 -->
    <param-name>savePath</param-name>
    <param-value>uploads</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>FileUploadServlet</servlet-name>
    <url-pattern>/servlet/FileUploadServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

同时在项目的根目录下创建文件夹 uploads (可以就在WebRoot中创建)


步骤四:创建显示上传结果的页面:fileUploadResult.jsp

<%@ page language="java" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>文件上传</title>
  </head>
  <body>
  <p>
      ${requestScope['message'] }<br/>
  </p>
  </body>
</html>

效果展示











请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客