文件上传下载代码

本文介绍了一个使用Java实现的文件上传系统,该系统能够处理文件上传、删除及下载等功能,并将文件信息保存到数据库中。系统采用了Spring框架进行业务逻辑处理,并利用了Apache Commons FileUpload库来解析上传的文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBDao {
   private static String url = "jdbc:mysql://localhost:3306/homework?useUnicode=true&characterEncoding=UTF-8";
   private static String user = "root";
   private static String password = "root";
   static {
      try {
         Class.forName("com.mysql.jdbc.Driver");
         // System.out.println("ok");
      } catch (ClassNotFoundException e) {
         // TODO Auto-generated catch block
         // System.out.println("no");
         e.printStackTrace();
      }
   }

   public static Connection getConnection() {
      Connection conn = null;
      try {
         conn = DriverManager.getConnection(url, user, password);
         // System.out.println("ok==");
      } catch (SQLException e) {
         // TODO Auto-generated catch block

         // System.out.println("no---");
         e.printStackTrace();
      }
      return conn;
   }

}
BaseDao.java
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class BaseDao { private Connection conn;  private PreparedStatement ps;  private ResultSet set;   public int[] addMoreData(Connection conn,String sql,Object[][] fields) throws SQLException{ this.conn=conn;  ps=conn.prepareStatement(sql);  if(fields!=null){ for(int i=0;i<fields.length;i++){ for(int j=0;j<fields[i].length;j++){ ps.setObject(j+1, fields[i][j]);  } ps.addBatch();  } } return ps.executeBatch();  } public int updateDB(Connection conn, String sql, Object[] fields) throws SQLException { this.conn = conn;  ps = conn.prepareStatement(sql);  if(fields!=null){ for (int i = 0; i < fields.length; i++) { ps.setObject(i + 1, fields[i]);  } } return ps.executeUpdate();  } public ResultSet selectDB(Connection conn,String sql,Object[] fields ) throws SQLException{ this.conn = conn;  ps = conn.prepareStatement(sql);  if(fields!=null){ for (int i = 0; i < fields.length; i++) { ps.setObject(i + 1, fields[i]);  } } return ps.executeQuery();  } public void closeAll(){ try { if(conn!=null){ conn.close();  } else if(ps!=null){ ps.close();  } else if(set!=null){ set.close();  } System.out.println("--------------");  } catch (SQLException e) { e.printStackTrace();  } } public ResultSet getTotalRecord(Connection conn,String sql)throws SQLException{ this.conn=conn;  ps=conn.prepareStatement(sql);  set=ps.executeQuery();  return set;  } public ResultSet getTotalRecord(Connection conn,String sql,Object[] fields)throws SQLException{ this.conn=conn;  ps=conn.prepareStatement(sql);  if(fields!=null){ for(int i=0;i<fields.length;i++){ ps.setObject(i+1, fields[i]);  } } set=ps.executeQuery();  return set; } }
import com.shopping.model.Files;
import java.sql.ResultSet;
import java.sql.SQLException;
public interface FileDao {
   public int addfile(Files file)throws SQLException;
   public int deleteById(int id)throws SQLException;
   public ResultSet select()throws SQLException;
   public ResultSet findFileById(int id)throws SQLException;  
}
import com.shopping.dao.api.BaseDao;
import com.shopping.dao.api.DBDao;
import com.shopping.dao.api.FileDao;
import com.shopping.model.Files;
import org.springframework.stereotype.Repository;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
@Repository
public class FileDaoImpl extends BaseDao implements FileDao {
   @Override
   public int addfile(Files file) throws SQLException {
      String sql="insert into files(file_name,file_desc,file_auto_name,user_name)values(?,?,?,?)";
      Connection conn= DBDao.getConnection();
      Object[] fields={file.getFile_name(),file.getFile_desc(),file.getFile_auto_name(),file.getUser_name()};
      return super.updateDB(conn, sql, fields);
   
   }
   @Override
   public int deleteById(int id) throws SQLException {
      String sql="delete from files where id=?";
      Object[] fields={id};
      Connection conn= DBDao.getConnection();
      return super.updateDB(conn, sql, fields);
      
   }

   @Override
   public ResultSet select() throws SQLException {
      String sql="select * from files";
      Connection conn=DBDao.getConnection();
      return super.selectDB(conn, sql, null);
      
   }

   @Override
   public ResultSet findFileById(int id) throws SQLException {
      String sql="select * from files where id=?";
      Object[] fields={id};
      Connection conn=DBDao.getConnection();
      return super.selectDB(conn, sql, fields);
      
   }

}
package com.shopping.model;
public class Files { private int id;  private String file_name;  private String file_desc;  private String file_auto_name;  private String user_name;  public int getId() { return id;  } public void setId(int id) { this.id = id;  } public String getFile_name() { return file_name;  } public void setFile_name(String file_name) { this.file_name = file_name;  } public String getFile_desc() { return file_desc;  } public void setFile_desc(String file_desc) { this.file_desc = file_desc;  } public String getFile_auto_name() { return file_auto_name;  } public void setFile_auto_name(String file_auto_name) { this.file_auto_name = file_auto_name;  } public String getUser_name() { return user_name;  } public void setUser_name(String user_name) { this.user_name = user_name;  } public Files(int id, String file_name, String file_desc, String file_auto_name, String user_name) { super();  this.id = id;  this.file_name = file_name;  this.file_desc = file_desc;  this.file_auto_name = file_auto_name;  this.user_name = user_name;  } public Files() { super();  } public Files(String file_name, String file_desc, String file_auto_name, String user_name) { super();  this.file_name = file_name;  this.file_desc = file_desc;  this.file_auto_name = file_auto_name;  this.user_name = user_name;  } @Override  public String toString() { return "Files [id=" + id + ", file_name=" + file_name + ", file_desc=" + file_desc + ", file_auto_name="  + file_auto_name + ", user_name=" + user_name + "]";  } } 
package com.shopping.service.api;
import com.shopping.model.Files;
import java.util.ArrayList;
public interface FileService {
   public int addfile(String file_name, String file_desc, String file_auto_name, String user_name);
   public int delete(int id);
   public ArrayList<Files> selectAll();
   public Files selectById(int id);
}
FileServiceImpl.java
package com.shopping.service.imp;
import com.shopping.dao.api.FileDao;
import com.shopping.model.Files;
import com.shopping.service.api.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@Service
public class FileServiceImpl implements FileService {
   @Autowired
   FileDao file;
   @Override
   public int addfile(String file_name, String file_desc, String file_auto_name, String user_name) {
      // TODO Auto-generated method stub
      Files files=new Files(file_name,file_desc,file_auto_name,user_name);
      int t=0;
      try {
         t=file.addfile(files);
      } catch (SQLException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      return t;
   }

   @Override
   public int delete(int id) {
      int t=0;
      try {
         t=file.deleteById(id);
      } catch (SQLException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      return t;
   }

   @Override
   public ArrayList<Files> selectAll() {
      ResultSet set=null;
      ArrayList<Files> list=new ArrayList<Files>();
      try {
         set=file.select();
         while(set.next()){
            int id=set.getInt("id");
            String file_name=set.getString("file_name");
            String file_desc=set.getString("file_desc");
            String file_auto_name=set.getString("file_auto_name");
            String user_name=set.getString("user_name");
            list.add(new Files(id,file_name,file_desc,file_auto_name,user_name));
            
         }
      } catch (SQLException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      return list;
   }

   @Override
   public Files selectById(int id) {
      Files file1=new Files();
      ResultSet set=null;
      try {
         set=file.findFileById(id);
         if(set.next()){
            
            
            file1.setId(id);
            file1.setFile_name(set.getString("file_name"));
            file1.setFile_desc(set.getString("file_desc"));
            file1.setFile_auto_name(set.getString("file_auto_name"));
            
            file1.setUser_name(set.getString("user_name"));
            
         }
      } catch (SQLException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      return file1;
   }

}


package com.shopping.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 com.shopping.model.Files;
import com.shopping.serviceimpl.FileServiceImpl;
import com.shopping.utils.getDate;

public class FileServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String p = request.getParameter("p");
        System.out.println(p);
        if ("doUpFile".equals(p)) {
            doUpFile(request, response);
        } else if ("del".equals(p)) {
            del(request, response);
        } else if ("doma".equals(p)) {
            doma(request, response);
        } else if ("download".equals(p)) {
            download(request, response);
        }
    }
    //得到了解析器
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    //判断上传是文件还是表单
    boolean result = servletFileUpload.isMultipartContent(request);
    System.out.print(result);
    Date date = new Date();
    String file_name = null;
    String file_desc = null;
    String autoName = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
    System.out.print(autoName);
    String username = String.valueOf(request.getSession().getAttribute("loginuser"));
    if(result){
        try {
            List<FileItem> fileitems = null;
            fileitems = servletFileUpload.parseRequest(request);
            System.out.println(autoName + "----------------------------------------------" + username);
        for (FileItem fileitem : fileitems) {
            //相当于表单元素的input里的name属性
            if (fileitem.isFormField()) {
                String fieldname = fileitem.getFieldName();
                String value = fileitem.getString("utf-8");
                //解决代码乱码的问题
                if ("file_name".equals(fieldname)) {
                    file_name = value;
                } else if ("file_desc".equals(fieldname)) {
                    file_desc = value;
                }
            } else {
                InputStream inputStream = fileitem.getInputStream();
                if (inputStream != null && inputStream.available() > 0) {
                    //得到文件名
                    String filename = fileitem.getName();
                    int index = filename.lastIndexOf(".");
                    String ext = filename.substring(index);
                    System.out.print(filename + "   " + ext);
                    autoName += ext;
                    String path = getServletContext().getRealPath("/uploadfile");
                    System.out.println(path + "89999999999999999999999");
                    File file = new File(path, autoName);
                    System.out.println(file + "3456789-------------");
                    //得到一个输出流,输出到服务器的磁盘
                    FileOutputStream outputStream = new FileOutputStream(file);
                    //一次上传1kb
                    byte[] datas = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(datas)) > 0) {
                        //读进多少字节,就写出多少字节
                        outputStream.write(datas, 0, len);
                    }
                    outputStream.flush();
                    outputStream.close();
                }
            }
        }
    } catch (FileUploadException e) {
// TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

    //调用service层的方法把相应的数据写到数据库
    FileServiceImpl service = new FileServiceImpl();
    int t = service.addfile(file_name, file_desc, autoName, username);
    if(t>0){
        response.getWriter().print("<script>alert('上传成功!'); location.href='FileServlet?p=doma';</script>");
    }

}
    public void doma(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        FileServiceImpl service = new FileServiceImpl();
        ArrayList<Files> file = service.selectAll();
        request.setAttribute("file", file);
        request.getRequestDispatcher("/Admin/files/fileshow.jsp").forward(request, response);
    }

    public void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        FileServiceImpl service = new FileServiceImpl();
        Files f = service.selectById(id);
        String path = "/uploadfile/" + f.getFile_auto_name();
        String realPath = getServletContext().getRealPath(path);
        File file = new File(realPath);
        boolean delete = file.delete();
        int t = service.delete(id);
        if (delete && t > 0) {
            response.getWriter().print("<script>alert('删除成功!');location.href='FileServlet?p=doma';</script>");
        }
    }

    public void download(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        int id = Integer.parseInt(request.getParameter("id"));
        FileServiceImpl fs = new FileServiceImpl();
        Files f = fs.selectById(id);
        String path = "/uploadfile/" + f.getFile_auto_name();
        String realPath = getServletContext().getRealPath(path);
        String auto_name = f.getFile_auto_name();
        //auto_name=URLEncoder.encode(auto_name, "utf-8");
        String ext = auto_name.substring(auto_name.lastIndexOf("."));
        String fileName = f.getFile_name();
        fileName += ext;
        //处理可能会出现的乱码问题
        //fileName=URLEncoder.encode(fileName,"utf-8");
        //确定流来下载文件FileInputStream input=new FileInputStream(realPath);
        response.reset();
        //response.setContentLength(input.available());
        // response.setContentType("charset=UTF-8");
        String agent = (String) request.getHeader("USER-AGENT"); 
        boolean isFireFox = (agent != null && agent.toLowerCase().indexOf("firefox") != -1);
        if (isFireFox) {
            fileName = (new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));   
        } else {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //response.reset();
        //response.setHeader("Content-Disposition", "attachment; filename="+fileName);
        OutputStream out = response.getOutputStream();
        byte[] buf = new byte[1024];
        int i = 0;
        while ((i = input.read(buf)) > 0) {
            out.write(buf, 0, i);
        }
        input.close();
        out.flush();
        out.close();
        System.out.print("下载完成");
    }

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

public class LoadServlet extends HttpServlet {
    /**
     * 载文件,通过OutputStream输出流 
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        //1.获取要下载的文件的绝对路径
       String realPath = this.getServletContext().getRealPath("/load/ceshi.txt");
        //2.获取要下载的文件名
       String fileName = realPath.subString(realPath.lastIndexOf("\\") + 1);
       String userAgent = request.getHeader("User-Agent");
        //针对IE或者以IE为内核的浏览器:
       if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
           fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
       } else {
        //非IE浏览器的处理:
           fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
       }
        //3.设置content-disposition响应头控制浏览器以下载的方式打开文件
       response.setHeader("content-disposition", "attachment;filename=" + fileName);
        //4.获取要下载的文件输入流
       InputStream in = new FileInputStream(realPath);


       int len = 0;
        //5.创建书缓冲区
       byte[] buffer = new byte[1024];
        //6.通过response对象获取OutputStream输出流对象
       OutputStream os = response.getOutputStream();
        //7.将FileInputStream流对象写入到buffer缓冲区
       while ((len = in.read(buffer)) > 0) {
           os.write(buffer, 0, len);
       }
        //8.关闭流
       in.close();
       os.close();
   }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值