java使用common-fileupload实现文件上传

作者:Bird 时间:2022-03-06 03:21:08 

文件上传是网站非常常用的功能,直接使用Servlet获取上传文件还得解析请求参数,比较麻烦,所以一般选择采用apache的开源工具,common-fileupload.这个jar包可以再apache官网上面找到,也可以在struts的lib文件夹下面找到,struts上传的功能就是基于这个实现的。

common-fileupload是依赖于common-io这个包的,所以还需要下载这个包。然后导入到你的项目路径下面。

使用代码如下


package oop.hg.ytu.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oop.hu.ytu.dao.UploadDomain;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Upload extends HttpServlet {

/**
  * 处理用户上传请求
  */
 private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
 // String describe = request.getParameter("describe");
   DiskFileItemFactory factory = new DiskFileItemFactory();
   @SuppressWarnings("deprecation")
   String path = request.getRealPath("/upload");//设置磁盘缓冲路径

factory.setRepository(new File(path));
   factory.setSizeThreshold(1024*1024);//设置创建缓冲大小

ServletFileUpload upload = new ServletFileUpload(factory);
   upload.setSizeMax(-1);//设置上传文件限制大小,-1无上限
   try {
     @SuppressWarnings("unchecked")
     List<FileItem> list = upload.parseRequest(request);
     String va = null;
     for(FileItem item : list){
   //   String name = item.getFieldName();
       if(item.isFormField()){//判断是否是文件流

va = item.getString("UTF-8");
       // System.out.println(name+"="+va);
     ///   request.setAttribute(name, value);
       }else{
         String value = item.getName();//会将完整路径名传过来
         int start = value.lastIndexOf("\\");
         String fileName = value.substring(start+1);
     //   request.setAttribute(name, fileName);
         InputStream in = item.getInputStream();
         UploadDomain dao = new UploadDomain();
         //item.write(new File(realPath,fileName));
         int index = fileName.lastIndexOf(".");
         String realFileName = fileName.substring(0,index);
         String type = fileName.substring(index+1);
         dao.insert(in, realFileName,type,va);//放入到数据库中

}
     }
   } catch (Exception e) {

e.printStackTrace();
   }
 }

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

}

}

 这里分别判断是否是上传的流或者表单里面的参数,比如文本框提交信息,然后将他们插入到数据库中。数据库插入
代码如下


package oop.hu.ytu.dao;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import oop.hg.ytu.utils.JdbcUtils;

/**
* 提供文件上传支持
* @author Administrator
*
*/
public class UploadDomain {
 /**
  * 将上传的文件流放入到数据库中
  */
 public void insert(InputStream in, String fileName, String type,String describe) throws Exception{//向数据库中写入图片  
   Connection conn = null;  
   PreparedStatement ps = null;  
   ResultSet rs = null;  
   System.out.println(describe);
   try {  
     // 2.建立连接  
     conn = JdbcUtils.getConnection();
     // 3.创建语句  
     String sql = "insert into fileupload(file,filename,type,des) values (?,?,?,?)";  
     ps = conn.prepareStatement(sql);  
     ps.setBlob(1, in);
     ps.setString(2, fileName);
     ps.setString(3, type);
     ps.setString(4, describe);
     // 4.执行语句  
     ps.executeUpdate();  

in.close();  

} finally {  
     JdbcUtils.free(rs, ps, conn);  
   }  
 }  
}

可能会遇到数据库默认问价大小限制,需要在mysql安装目录下面的my.ini下面更改如下配置,
[mysqld] 
max_allowed_packet=64M 

这样就可以了。当然,注意编码格式。上传文件搞定。还有就是我的一个列名设置为describe,结果和Mysql保留字冲
突,出现无法插入信息现象,以后一定要注意。

标签:java,common,fileupload,文件上传
0
投稿

猜你喜欢

  • C# 时间与时间戳互转的方法(13位)

    2023-12-04 10:26:39
  • 如何在IDEA中对 hashCode()和 equals() 利用快捷键快速进行方法重写

    2021-11-04 19:06:13
  • mybatis-plus分页查询的实现示例

    2023-11-25 04:57:57
  • C# Winform 调用系统接口操作 INI 配置文件的代码

    2023-03-04 11:49:54
  • 浅谈Java自定义类加载器及JVM自带的类加载器之间的交互关系

    2021-09-12 23:37:24
  • Maven 错误找不到符号的解决方法

    2021-07-19 09:03:02
  • Android应用程序转到后台并回到前台判断方法

    2022-11-12 19:49:35
  • C#微信公众号开发 微信事件交互

    2023-04-22 21:18:31
  • Mybatis 动态SQL的几种实现方法

    2023-11-10 12:15:15
  • Flutter 分页功能表格控件详细解析

    2023-09-22 20:02:45
  • java swing实现简单的五子棋游戏

    2022-04-16 22:10:10
  • 利用栈使用简易计算器(Java实现)

    2023-07-22 02:02:11
  • 解决IDEA maven 项目修改代码不生效,mvn clean、install后才生效

    2022-06-19 12:17:06
  • 浅谈java中定义泛型类和定义泛型方法的写法

    2023-04-19 14:28:59
  • spring框架集成flyway项目的详细过程

    2023-09-14 11:47:14
  • Mybatis-Plus使用updateById()、update()将字段更新为null

    2023-11-26 01:53:42
  • springboot 中整合mybatis多数据源不使用JPA

    2023-03-01 08:43:02
  • java基于swing实现的五子棋游戏代码

    2023-09-24 17:31:17
  • Java详细分析梳理垃圾回收机制

    2023-10-30 04:02:33
  • Java concurrency之共享锁和ReentrantReadWriteLock_动力节点Java学院整理

    2022-06-16 09:17:25
  • asp之家 软件编程 m.aspxhome.com