文件上传下载

package cn.edu.hbcf.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.hbcf.common.jackjson.JackJson;
import cn.edu.hbcf.common.vo.ExtReturn;

public class FileDownLoadUtils {
    private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
    /**
     * 
     * @param filePath
     * @param fileName
     * @param response
     */
    public static void  downloadFile(String filePath,String fileName,HttpServletResponse response){
        InputStream input = null;
        ServletOutputStream output = null;
        try {
            File downloadFile = new File(filePath);
            // 判断文件夹是否存在,不存在则创建
            if (!downloadFile.getParentFile().exists()) {
                downloadFile.getParentFile().mkdirs();
            }
            // 判断是否存在这个文件
            if (!downloadFile.isFile()) {
                // 创建一个
                FileUtils.touch(downloadFile);
            }           
        
            //response.setContentType("application/octet-stream;charset=UTF-8");
            response.setContentType("application/x-download");  
            response.setCharacterEncoding("UTF-8");
           
//            response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
          //解决中文乱码  
            response.setHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("UTF-8"),"iso-8859-1").replace(" ", "_"));  

            input = new FileInputStream(downloadFile);
            output = response.getOutputStream();
            IOUtils.copy(input, output);
            
        } catch (Exception e) {
            logger.error("Exception: ", e);
        } finally {
            
                try {
                    if(output != null){
                        output.flush();
                        output.close();
                    }
                    if(input != null){
                        input.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            
//            IOUtils.closeQuietly(output);
//            IOUtils.closeQuietly(input);
        }
    }
    
    

    public static String fileUpload(MultipartFile file, HttpServletRequest request,String saveFolder,long maxSize){
        String returnMsg  = null;
        try {
            
            // 保存的地址
            String savePath = request.getSession().getServletContext().getRealPath("/"+saveFolder);
            if(maxSize!=0 && file.getSize()>maxSize){
                returnMsg = JackJson.fromObjectToJson(new ExtReturn(false, "文件大小超过了"+maxSize/(1024*1024)+"M了,上传失败!"));
                return returnMsg;
            }
            // 上传的文件名 //需要保存
            String uploadFileName = file.getOriginalFilename();
            // 获取文件后缀名 //需要保存
            String fileType = StringUtils.substringAfterLast(uploadFileName, ".");
            // 以年月/天的格式来存放
            String dataPath = DateFormatUtils.format(new Date(), "yyyy-MM" + File.separator + "dd");
            // uuid来保存不会重复
            String saveName = UUID.randomUUID().toString().replace("-", "");
            // 最终相对于upload的路径,解决没有后缀名的文件 //需要保存
            // 为了安全,不要加入后缀名
            // \2011-12\01\8364b45f-244d-41b6-bbf4-8df32064a935,等下载的的时候在加入后缀名
            String finalPath = File.separator + dataPath + File.separator + saveName + ("".equals(fileType) ? "" : "." + fileType);
            logger.debug("savePath:{},finalPath:{}", new Object[] { savePath, finalPath });
            File saveFile = new File(savePath + finalPath);
            // 判断文件夹是否存在,不存在则创建
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            // 写入文件
            FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
            // 保存文件的基本信息到数据库
            StringBuffer buffer = new StringBuffer();
            buffer.append("{success:true,fileInfo:{'fileName':'").append(uploadFileName).append("',");
            buffer.append("'filePath':'").append(savePath.replace("\\", "/")+finalPath.replace("\\", "/")).append("',");          
            buffer.append("'projectPath':'").append(saveFolder.replace("\\", "/")).append(finalPath.replace("\\", "/")).append("',");
            buffer.append("'storeName':'").append(saveName + ("".equals(fileType) ? "" : "." + fileType));
            buffer.append("'}}");
            returnMsg = buffer.toString();
            
        } catch (Exception e) {
            logger.error("Exception: ", e);
        }
        return returnMsg;
    }
    
    public static File upload(MultipartFile file,String saveFolder){
         File f = null;
         try {
            // 上传的文件名 //需要保存
            String uploadFileName = file.getOriginalFilename();
            // 获取文件后缀名 //需要保存
            String fileType = StringUtils.substringAfterLast(uploadFileName, ".");
            // 以年月/天的格式来存放
//            String dataPath = DateFormatUtils.format(new Date(), "yyyy-MM" + File.separator + "dd");
            // uuid来保存不会重复
            String saveName = UUID.randomUUID().toString().replace("-", "");
            // 最终相对于upload的路径,解决没有后缀名的文件 //需要保存
            // 为了安全,不要加入后缀名
            // \2011-12\01\8364b45f-244d-41b6-bbf4-8df32064a935,等下载的的时候在加入后缀名
            String finalPath = saveFolder + saveName + ("".equals(fileType) ? "" : "." + fileType);
            logger.debug("finalPath:{}", new Object[] {  finalPath });
            File saveFile = new File(finalPath);
            // 判断文件夹是否存在,不存在则创建
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            // 写入文件
            FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
    
            f = new File(finalPath.replace("\\", "/"));
        } catch (Exception e) {
            logger.error("Exception: ", e);
        }
        return f;
    }

    public static File upload(MultipartFile file, HttpServletRequest request,String saveFolder){
        File f = null;
        try {
            
            // 保存的地址
            String savePath = request.getSession().getServletContext().getRealPath("/");
            if(saveFolder != null){
                  savePath += saveFolder;
            }
            // 上传的文件名 //需要保存
            String uploadFileName = file.getOriginalFilename();
            // 获取文件后缀名 //需要保存
            String fileType = StringUtils.substringAfterLast(uploadFileName, ".");
            // 以年月/天的格式来存放
       //    String dataPath = DateFormatUtils.format(new Date(), "yyyy-MM" + File.separator + "dd");
            // uuid来保存不会重复
            String saveName = UUID.randomUUID().toString().replace("-", "");
            // 最终相对于upload的路径,解决没有后缀名的文件 //需要保存
            // 为了安全,不要加入后缀名
            // \2011-12\01\8364b45f-244d-41b6-bbf4-8df32064a935,等下载的的时候在加入后缀名
            String finalPath =  File.separator + saveName + ("".equals(fileType) ? "" : "." + fileType);
            logger.debug("savePath:{},finalPath:{}", new Object[] { savePath, finalPath });
            f = new File(savePath + finalPath);
            // 判断文件夹是否存在,不存在则创建
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdirs();
            }
            // 写入文件
            FileUtils.writeByteArrayToFile(f, file.getBytes());
 
          //  f = new File(savePath.replace("\\", "/")+finalPath.replace("\\", "/"));
        } catch (Exception e) {
            logger.error("Exception: ", e);
        }
        return f;
    }

    /**
     * 创建文件夹
     * @param request
     * @param saveFolder
     * @return
     */
    public static File createFile(HttpServletRequest request,String saveFolder){
        // 保存的地址
        String savePath = request.getSession().getServletContext().getRealPath("/");
        if(saveFolder != null){
              savePath += saveFolder;
        }
        File file=new File(savePath);
     // 判断文件夹是否存在,不存在则创建
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }
}

 

posted @ 2015-11-06 15:36  花语苑  阅读(297)  评论(0编辑  收藏  举报