java文件上传Demo(必看篇)

所属分类: 软件编程 / java 阅读数: 41
收藏 0 赞 0 分享

说到文件上传我们要做到:

1.引入两个包:commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar

2.将form改为上传文件模式:enctype="multipart/form-data"

3.开始编写相关代码

这里会用到几个关键的类:磁盘文件工厂DiskFileItemFactory ; 创建servlet文件上传类:ServletFileUpload

还有几个重要的方法:DiskFileItemFactory类用于将以临时文件形式保存在磁盘上的存放目录的方法setRepository;

ServletFileUpload类得到表单中所有的数据,得到form表单中所有的元素方法:parseRequest

下面看具体代码:

说明以这种方式上传文件是保存在服务器端的!

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
 
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;
import org.apache.commons.io.FileUtils;
 
 
public class UploadServlet extends HttpServlet {
 
  /**
   * Constructor of the object.
   */
  public UploadServlet() {
    super();
  }
 
  /**
   * Destruction of the servlet. <br>
   */
  public void destroy() {
    super.destroy(); // Just puts "destroy" string in log
    // Put your code here
  }
 
  /**
   * The doGet method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to get.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
 
    this.doPost(request, response);
  }
 
  /**
   * The doPost method of the servlet. <br>
   *
   * This method is called when a form has its tag value method equals to post.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
 
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    DiskFileItemFactory sf= new DiskFileItemFactory();//实例化磁盘被文件列表工厂
    String path = request.getRealPath("/upload");//得到上传文件的存放目录
    sf.setRepository(new File(path));//设置文件存放目录
    sf.setSizeThreshold(1024*1024);//设置文件上传小于1M放在内存中
    String rename = "";//文件新生成的文件名
    String fileName = "";//文件原名称
    String name = "";//普通field字段
    //从工厂得到servletupload文件上传类
    ServletFileUpload sfu = new ServletFileUpload(sf);
     
    try {
      List<FileItem> lst = sfu.parseRequest(request);//得到request中所有的元素
      for (FileItem fileItem : lst) {
        if(fileItem.isFormField()){
          if("name".equals(fileItem.getFieldName())){
            name = fileItem.getString("UTF-8");
          }
        }else{
          //获得文件名称
          fileName = fileItem.getName();
          fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
          String houzhui = fileName.substring(fileName.lastIndexOf("."));
          rename = UUID.randomUUID()+houzhui;
          fileItem.write(new File(path, rename));
        }
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
     
    System.out.println("普通字段"+name);
    System.out.println("文件名称"+fileName);
    System.out.println("修改后生成的文件名称"+rename);
    response.sendRedirect("ok.jsp");
    out.flush();
    out.close();
  }
 
  /**
   * Initialization of the servlet. <br>
   *
   * @throws ServletException if an error occurs
   */
  public void init() throws ServletException {
    // Put your code here
  }
 
}

index.jsp页面:

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>  
  <title>文件测试界面</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">
 </head>
 <body>
  <div align="center">
  <form action="UploadServlet" enctype="multipart/form-data" method="post">
    名称:<input name="name" /> <br>
    图片:<input name="img" type="file"/><br>
    <input type="submit" value="提交" />  
    <input type="reset" value="重置" />
  </form>
  </div>
 </body>
</html>

ok.jsp页面:

<body>
  <h1 align="center">上传文件成功!</h1>
 </body>

实现效果就不截图了,有需要自己那过去用!

以上这篇java文件上传Demo(必看篇)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Java concurrency之锁_动力节点Java学院整理

这篇文章主要为大家详细介绍了Java concurrency之锁的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Java8新特性之StampedLock_动力节点Java学院整理

本文从synchronized、Lock到Java8新增的StampedLock进行对比分析,对Java8新特性之StampedLock相关知识感兴趣的朋友一起看看吧
收藏 0 赞 0 分享

Java8新特性之lambda的作用_动力节点Java学院整理

我们期待了很久lambda为java带来闭包的概念,但是如果我们不在集合中使用它的话,就损失了很大价值。现有接口迁移成为lambda风格的问题已经通过default methods解决了,在这篇文章将深入解析Java集合里面的批量数据操作解开lambda最强作用的神秘面纱。
收藏 0 赞 0 分享

Java8新特性之Base64详解_动力节点Java学院整理

这篇文章主要为大家详细介绍了Java8新特性之Base64的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Java8新特性之JavaFX 8_动力节点Java学院整理

这篇文章主要介绍了Java8新特性之JavaFX 8的相关知识,非常不错,具有参考借鉴价值,需要的朋友参考下吧
收藏 0 赞 0 分享

将本地jar包安装进入maven仓库(实现方法)

下面小编就为大家带来一篇将本地jar包安装进入maven仓库(实现方法)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

浅谈Java finally语句到底是在return之前还是之后执行(必看篇)

下面小编就为大家带来一篇浅谈Java finally语句到底是在return之前还是之后执行(必看篇)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

基于Java并发容器ConcurrentHashMap#put方法解析

下面小编就为大家带来一篇基于Java并发容器ConcurrentHashMap#put方法解析。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

详解Spring Boot Profiles 配置和使用

本篇文章主要介绍了详解Spring Boot Profiles 配置和使用,具有一定的参考价值,有兴趣的可以了解一下
收藏 0 赞 0 分享

详解Spring Boot 属性配置和使用

本篇文章主要介绍了详解Spring Boot 属性配置和使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多