org.apache.commons.fileupload 文件上传至数据库

package cn.com.capture.service.rest.resource.upload.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

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

import cn.com.capture.common.db.BaseDO;
import cn.com.capture.service.rest.resource.base.BaseAuthResource;
import cn.com.capture.service.rest.resource.upload.FileUpload;

public class FileUploadImpl extends BaseAuthResource implements FileUpload {

 @Override
 public Representation doFileUpload(Representation resp) {
   executeUpload(httpServletRequest);
  return null;
 }

 /**
  * 处理上传文件
  *
  * @param request
  * @throws UnsupportedEncodingException
  */
 public void executeUpload(HttpServletRequest request) {
//  request.setCharacterEncoding("UTF-8");
  String gps_x = "123.122323";
  String gps_y = "123.122323";
  String user = "capture";
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  if (isMultipart == true) {
   try {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("iso8859-1");
    List<FileItem> fileItems = upload.parseRequest(request); // 得到所有的表单域,它们目前都被当作FileItem
    String uploadPath = "d:\\upload\\";
    File file = new File(uploadPath);
    if (!file.exists()) { // 如果没有此目录就创建此目录
     file.mkdir();
    }
    int faultid = 0;
    Iterator<FileItem> iter = fileItems.iterator();
    while (iter.hasNext()) { // 依次处理每个表单域
     FileItem item = (FileItem) iter.next();
     if (item.isFormField()) { // 如果item是正常的表单域
      String faultremark = new String(item.getString().getBytes("iso8859-1"),"utf-8"); //中文编码
//      System.out.println("故障描述:   "+faultremark);
      //设置相同描述信息 并返回id 给以其附件信息id
      faultid = setFaultPointInfo(faultremark,gps_x,gps_y,user);
     } else {  // 如果item是文件上传表单域
      String filename = item.getName();
      //new String(item.getName().getBytes("iso8859-1"),"utf-8");  //得到文件名
       String filetype = filename.substring(filename.lastIndexOf("."),filename.length()); //文件后缀
      InputStream is = item.getInputStream(); //此处已经得到上传文件的输入流
      String filepath = uploadPath +filename;  //此处的filename可以改名存储
      if (new File(filepath).exists()) { // 上传文件是否存在
       new File(filepath).delete(); // 存在就删除
      }
      if (!filepath.equals("")) { // 如果文件名不为空
       FileOutputStream fos = new FileOutputStream(filepath);
       byte[] buffer = new byte[10240];
       int count = 0;
       while ((count = is.read(buffer)) > 0) {
        fos.write(buffer, 0, count); // 开始上传至目录文件
       }
       fos.close();
       is.close();
       FileInputStream inStream = new FileInputStream(new File(filepath)); //根据文件路径得到其输入流
       writeMedia(faultid, inStream, filepath,filetype); // 根据文件照片信息写入数据库
       System.out.println("文件上传成功");
      }
     }
    }
//    readMedia("andiioreUser");
    System.out.println("取出文件成功");
   } catch (Exception e) {
    e.printStackTrace();
   }
  } else {
   System.out.println("请求表单类型不对。。。。the enctype must be multipart/form-data");
  }
 }

 /**
  * 设置某个故障点信息 并返回表记录id
  *
  * @return
  */
 public int setFaultPointInfo(String remarks, String gps_x, String gps_y,
   String username) {
  String inserSql = "insert into C_WEB_FAULTPONTINFO(REMARK,GPS_X,GPS_Y,USERNAME) values('"
    + remarks
    + "','"
    + gps_x
    + "','"
    + gps_y
    + "','"
    + username
    + "')";
  BaseDO.getInstance().executeUpdate(inserSql);
  return BaseDO.getInstance().getTableRecord("C_WEB_FAULTPONTINFO_ID",
    "C_WEB_FAULTPONTINFO");
 }

 /**
  * 根据故障点信息设置故障点的各种媒体信息
  *
  * @return
  */
 public boolean writeMedia(int faultid, FileInputStream inStream,
   String faultpath, String faultinfo) {
  boolean flag = false;
  String sql = "insert into C_WEB_FAULTMEDIA(C_WEB_FAULTPONTINFO_ID,FAULTMEDIAFILE,FAULTMEDIAPATH,FAULTINFO) values(?,?,?,?)";
  BaseDO bd = BaseDO.getInstance();
  Connection conn = bd.getConnection();
  PreparedStatement pstmt = null;
  try {
   pstmt = conn.prepareStatement(sql);
   pstmt.setInt(1, faultid);
   pstmt.setBinaryStream(2, inStream, inStream.available()); // 字符流写入数据库
   pstmt.setString(3, faultpath);
   pstmt.setString(4, faultinfo);
   pstmt.executeUpdate(); // 执行插入操作
   inStream.close();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   bd.close(pstmt, conn);
  }
  return flag;
 }

 /**
  * 根据用户名读取该用户上传的媒体文件
  * @param username
  * @return
  */
 public String readMedia(String username) {
  String sql = "select FAULTMEDIAPATH,FAULTMEDIAFILE from C_WEB_FAULTMEDIA a,C_WEB_FAULTPONTINFO b where A.C_WEB_FAULTPONTINFO_ID (+)= B.C_WEB_FAULTPONTINFO_ID"
    + " and B.USERNAME = '"+username+"'";
  BaseDO bd = BaseDO.getInstance();
  Connection conn = bd.getConnection();
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  try {
   pstmt = conn.prepareStatement(sql);
   rs = pstmt.executeQuery();
   while(rs.next()){
    FileOutputStream outStream = new FileOutputStream(rs.getString("FAULTMEDIAPATH")); //rs.getString("FAULTMEDIAPATH")
    InputStream inStream = rs.getBinaryStream("FAULTMEDIAFILE"); //得到数据库存放媒体文件的值
    byte[] buf = new byte[10240];
    int len;
    while ((len = inStream.read(buf)) > 0) {
     outStream.write(buf, 0, len);
    }
    inStream.close();
    outStream.close();
   }
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   bd.close(rs, pstmt, conn);
  }
  return null;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值