zoukankan      html  css  js  c++  java
  • JAVA实现文件上传

     

    代码如下:

          还要两个jar包
          前台页面:
          

    01 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    02 <%
    03 String path = request.getContextPath();
    04 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    05 %>
    06  
    07  
    08  
    09    
    10     <base href="<%=basePath%>">
    11      
    12     <title>My JSP 'index.jsp' starting page</title>
    13     <meta http-equiv="pragma" content="no-cache">
    14     <meta http-equiv="cache-control" content="no-cache">
    15     <meta http-equiv="expires" content="0">   
    16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    17     <meta http-equiv="description" content="This is my page">
    18     <!--
    19     <link rel="stylesheet" type="text/css" href="styles.css">
    20     -->
    21    
    22    
    23     <!--
    24       action:请求地址
    25       method:请求方式  get post
    26       enctype:multipart/form-data 以二进制的形式向服务器传递参数
    27      -->
    28       <form action="fileUp.do" method="post" enctype="multipart/form-data">
    29          <table>
    30             <tbody><tr>
    31                <td>请选择要上传的文件:</td>
    32                <td><input type="file" name="file"></td>
    33             </tr>
    34            <tr>
    35               <td><input type="submit" value="开始上传"></td>
    36            </tr>
    37          </tbody></table>
    38      </form>     
    39   
    后端代码:
    01 package com.zengda;
    02  
    03 import java.io.File;
    04 import java.io.IOException;
    05 import java.io.PrintWriter;
    06 import java.util.Iterator;
    07 import java.util.List;
    08  
    09 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12  
    13 import org.apache.commons.fileupload.FileItem;
    14 import org.apache.commons.fileupload.FileUploadException;
    15 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    16 import org.apache.commons.fileupload.servlet.ServletFileUpload;
    17  
    18 public class FileUpServlet extends HttpServlet{
    19     //重写HttpServlet里面的service方法
    20     public void service(HttpServletRequest request,HttpServletResponse response)
    21        throws IOException{
    22         request.setCharacterEncoding("UTF-8");//设置编码
    23         response.setCharacterEncoding("GBK");
    24         //基于磁盘文件项目创建一个工厂对象
    25         DiskFileItemFactory factory  = new DiskFileItemFactory();
    26         //创建一个新的文件上传对象
    27         ServletFileUpload upload = new ServletFileUpload(factory);
    28         try {
    29             //解析上传请求
    30             List items = upload.parseRequest(request);
    31             Iterator itr = items.iterator();//枚举方法 返回迭代器
    32             while (itr.hasNext()) {//如果迭代器有数据 返回true 没数据返回false
    33                  FileItem fileItem = (FileItem)itr.next();//获取FileItem对象
    34                  if(!fileItem.isFormField()){//判断是否为文件上传域 如果是文件上传域返回false  不是就返回true
    35                     long fileSize =  fileItem.getSize();//获取文件的大小
    36                     String fileName = fileItem.getName();//获取上传文件的名字(真实文件)
    37                     //构建一个临时对象,将文件暂时的保存在服务器的内存里面
    38                     File tempFile = new File(fileName);
    39                     //根据servlet上下文获取上传路径
    40                     String updatePath =  this.getServletContext().getRealPath("/upload");
    41                     //获取根目录对应的真实物理路径
    42                     File file = new File(updatePath,tempFile.getName());
    43                     //将文件上传
    44                     fileItem.write(file);
    45                     PrintWriter out = response.getWriter();//获取输出流
    46                     out.print("文件上传成功! ");
    47                     out.print("上传路径为: "+updatePath);
    48                     out.print("文件名: "+fileName);
    49                     out.print("文件的大小为: "+fileSize+" KB");
    50                  }
    51             }
    52         catch (FileUploadException e) {
    53             e.printStackTrace();
    54         catch (Exception e) {
    55             e.printStackTrace();
    56         }
    57          
    58     }
    59 }
    web.xml:
    01 <!--?xml version="1.0" encoding="UTF-8"?-->
    03   <display-name>FileUp</display-name>
    04   <welcome-file-list>
    05     <welcome-file>index.html</welcome-file>
    06     <welcome-file>index.htm</welcome-file>
    07     <welcome-file>index.jsp</welcome-file>
    08     <welcome-file>default.html</welcome-file>
    09     <welcome-file>default.htm</welcome-file>
    10     <welcome-file>default.jsp</welcome-file>
    11   </welcome-file-list>
    12    
    13   <!-- 定义一个servlet -->
    14   <servlet>
    15      <servlet-name>file</servlet-name>
    16      <servlet-class>com.zengda.FileUpServlet</servlet-class>
    17   </servlet>
    18    
    19   <!-- 配置访问路径 -->
    20   <servlet-mapping>
    21      <servlet-name>file</servlet-name>
    22      <url-pattern>/fileUp.do</url-pattern>
    23   </servlet-mapping>
    24 </web-app>
  • 相关阅读:
    idea的tomcat配置
    idea设置类文件的头部信息
    设置idea注释颜色
    Idea设置字体
    python 全栈开发,Day11(函数名应用,闭包,装饰器初识,带参数以及带返回值的装饰器)
    python 全栈开发,Day10(动态参数,命名空间,作用域,函数嵌套)
    python 全栈开发,Day9(函数的初始,返回值,传参,三元运算)
    python 全栈开发,Day8(文件操作)
    python 全栈开发,Day7(元组转换,列表以及字典的坑,集合,关系测试,深浅copy,编码补充)
    python 全栈开发,Day6补充(is,小数据池,编码转换)
  • 原文地址:https://www.cnblogs.com/zengda/p/4297779.html
Copyright © 2011-2022 走看看