码迷,mamicode.com
首页 > Web开发 > 详细

文件上传、下载 -- 网络云盘案例

时间:2016-09-28 02:09:27      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

package cn.gudan.yunpan.web.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.SQLException;

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

import sun.misc.BASE64Encoder;

import cn.gudan.yunpan.domain.Resource;
import cn.gudan.yunpan.service.ResourceService;

public class FileDownLoadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String idStr = request.getParameter("id");
        idStr = new String(idStr.getBytes("iso-8859-1"),"utf-8");
        
        //获取文件id
        int id = Integer.parseInt(idStr);
        
        try {
            //通过文件id从数据库获取其他信息
            ResourceService service = new ResourceService();
            
            Resource resource = service.findResource(id);
            
            File file = new File(resource.getSavepath(),resource.getUuidname());
            
            //判断文件是否存在
            if(file.isFile()){
                //文件存在
                //获取文件名称
                String filename = resource.getRealname();
                
                //设置请求头信息
                response.setContentType(this.getServletContext().getMimeType(filename));
               
                //获取浏览器版本
                /*
                  2.设置一个响应头,设置后的效果,就是无论返回的是否可以被浏览器解析,就是下载 。
                       response.setHeader("content-disposition","attachment;filename=下载文件名称");
                 */
                String agent = request.getHeader("User-agent");
                
              //处理浏览器乱码问题
                if (agent.contains("MSIE")) {
                    // IE浏览器
                    filename = URLEncoder.encode(filename, "utf-8");
                } else if (agent.contains("Firefox")) {
                    // 火狐浏览器
                    BASE64Encoder base64Encoder = new BASE64Encoder();
                    filename = "=?utf-8?B?"+base64Encoder.encode(filename.getBytes("utf-8"))+"?=";
                } else if (agent.contains("Chrome")) {
                    // google浏览器
                    filename = URLEncoder.encode(filename, "utf-8");
                } else {
                    // 其它浏览器
                    filename = URLEncoder.encode(filename, "utf-8");
                }
                
              //设置请求头信息
                response.setHeader("Content-Disposition",  "attachment;filename=" + filename);
                
                
                OutputStream os = response.getOutputStream();
                FileInputStream fis = new FileInputStream(file);
                byte[] b = new byte[1024*10];
                int len = -1;
                
                while((len = fis.read(b))!=-1){
                    
                    os.write(b, 0, len);
                    os.flush();
                }
                
                fis.close();
                
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        

    }

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

}

 

package cn.gudan.yunpan.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

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

import cn.gudan.yunpan.domain.Resource;
import cn.gudan.yunpan.service.ResourceService;

public class FileShow extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        ResourceService service = new ResourceService();
        
        try {
            List<Resource> resourceList = service.showFile();
            
            if(resourceList!=null){
                
                request.setAttribute("resourceList", resourceList);
                request.getRequestDispatcher("/download.jsp").forward(request, response);
                return;
            }
            
            request.setAttribute("msg", "没有文件信息");
            request.getRequestDispatcher("/download.jsp").forward(request, response);
            
            
        } catch (SQLException e) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("查询失败");
            e.printStackTrace();
        }

    }

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

}

 

package cn.gudan.yunpan.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
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.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
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.IOUtils;

import cn.gudan.yunpan.domain.Resource;
import cn.gudan.yunpan.service.ResourceService;
import cn.gudan.yunpan.utils.ResourceUtils;

public class FileUpLoadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        /*
         *Map<String, String[]> map = request.getParameterMap();
         *    request对象获取的map集合是不可变的。不能修改。
         *    只能自定义一个map集合 
         */
        Map<String, String[]> map = new HashMap<String, String[]>();
        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        
        ServletFileUpload upload = new ServletFileUpload(factory);
        
        //boolean flag = upload.isMultipartContent(request);
        //这两个方法是一样的效果。
        //判断请求是不是文件上传请求,相当于判断    encType="multipart/form-data"
        boolean flag = ServletFileUpload.isMultipartContent(request);
        
        if(flag){
            try {
                //设置文件名称的编码
                upload.setHeaderEncoding("utf-8");
                //获取组件集合
                List<FileItem> parseRequest = upload.parseRequest(request);
                //遍历组件
                for (FileItem fileItem : parseRequest) {
                    //判断组件是不是文件上传组件
                    if(fileItem.isFormField()){
                        //不是文件上传组件
                        //获取name组件属性:description
                        String fieldName = fileItem.getFieldName();
                        //添加到map集合
                        map.put(fieldName, new String[]{fileItem.getString("utf-8")});
                        
                    }else{
                        //是文件上传组件
                        //获取文件名称,因为浏览器不同,有的浏览器是全路径,所以需要截取
                        String filename = fileItem.getName();
                        filename =  filename.substring(filename.lastIndexOf("\\")+1);
                        
                        //获取UUID名称
                        String uuidFileName = ResourceUtils.getUUIDFileName(filename);
                        
                        //获取文件存储路径
                        String randomDirectory = this.getServletContext().getRealPath("WEB-INF/upload")+ResourceUtils.getRandomDirectory(filename);
                        
                        //根据目录创建File
                        File directory = new File(randomDirectory);
                        
                        //如果目录不存在,则创建目录
                        if(!directory.exists()){
                            //只能创建单层目录
                            //directory.mkdir();
                            //可以创建多重目录
                            directory.mkdirs();
                        }
                        //创建全路径及文件名的File
                        //new File()的参数可以是字符串,也可以是File对象,也可以两者组合
                        File file = new File(directory,uuidFileName);
                        
                        //保存文件
                        IOUtils.copy(fileItem.getInputStream(), new FileOutputStream(file));
                        //删除临时文件
                        fileItem.delete();
                        
                        //将属性封装到map集合
                        map.put("uuidname", new String[] { uuidFileName });
                        map.put("realname", new String[] { filename });
                        map.put("savepath", new String[] { randomDirectory });
                    }
                }
                /* 使用javaBean将属性封装到对象中 */
                Resource resource = new Resource();
                BeanUtils.populate(resource, map);
                
                //将记录存储到数据库中
                ResourceService service = new ResourceService();
                service.save(resource);
                
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
    }

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

}

 

package cn.gudan.yunpan.service;

import java.sql.SQLException;
import java.util.List;

import cn.gudan.yunpan.dao.ResourceDao;
import cn.gudan.yunpan.domain.Resource;

public class ResourceService {

    public void save(Resource resource) throws SQLException {
        new ResourceDao().save(resource);
    }

    public List<Resource> showFile() throws SQLException {
         return new ResourceDao().showFile();
    }

    public Resource findResource(int id) throws SQLException {
            return new ResourceDao().findResource(id);
    }

}

 

package cn.gudan.yunpan.service;

import java.sql.SQLException;
import java.util.List;

import cn.gudan.yunpan.dao.ResourceDao;
import cn.gudan.yunpan.domain.Resource;

public class ResourceService {

    public void save(Resource resource) throws SQLException {
        new ResourceDao().save(resource);
    }

    public List<Resource> showFile() throws SQLException {
         return new ResourceDao().showFile();
    }

    public Resource findResource(int id) throws SQLException {
            return new ResourceDao().findResource(id);
    }

}

 

文件上传、下载 -- 网络云盘案例

标签:

原文地址:http://www.cnblogs.com/gudanjava/p/5914882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!