java 单个上传文件, 批量上传文件,单个下载,批量打成zip压缩包下载文件(如果不能接受httpsevletrequest请求的文件可以使用MultipartFile[] files)

package net.wkang.intelligent_audit.hospitalization.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Configuration
public class FileUploadDownload {
    /**
     * 单文件上传
     * @param file
     * @return
     */
    public Map<String, Object> upload(MultipartFile file){
        Map<String, Object> map = new HashMap<String,Object>();
        if(file==null) {
            map.put("message", "没有发现文件!");
            return map;
        } 
        if (file.isEmpty()) {
            map.put("message", "文件不能为空!");
            return map;
        }
         // 获取文件名
        String fileName=file.getOriginalFilename();
      
            System.out.println("上传的文件名为:" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            System.out.println("上传的后缀名为:" + suffixName);
            // 文件上传后的路径
            String filePath = "upload/";
            // 解决中文问题,liunx下中文路径,图片显示问题
            // fileName = UUID.randomUUID() + suffixName;
            String absolutePath = new File(filePath + fileName).getAbsolutePath();//获取绝对路径
            map.put("path", absolutePath);
            System.out.println(absolutePath);
            File dest = new File(absolutePath);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
                map.put("message", "上传成功");
                return map;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            map.put("message", "上传失败");
            return map;
    }
    
    /**
     * 批量上传
     * @param orderId 
     * */
    public Map<String, Object> handleFileUpload(HttpServletRequest request, String orderId) {
        Map<String, Object> map = new HashMap<String,Object>();
        List<String> listFileName = new ArrayList<String>();
        List<String> listFilePath = new ArrayList<String>();
        System.out.println(request.getParameter("file"));
        
             List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                        .getFiles("file");
             String realPath = "upload/"+orderId+"/";
             File dest = new File(realPath + " ");
                // 检测是否存在目录
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                MultipartFile file = null;
                BufferedOutputStream stream = null;
                for (int i = 0; i < files.size(); ++i) {
                    file = files.get(i);
                    if (!file.isEmpty()) {
                        try {
                            byte[] bytes = file.getBytes();
                            stream = new BufferedOutputStream(new FileOutputStream(
                                    new File(realPath,file.getOriginalFilename())));
                            listFileName.add(file.getOriginalFilename());
                            listFilePath.add(realPath+file.getOriginalFilename());
                            stream.write(bytes);
                            stream.close();
                        } catch (Exception e) {
                            stream = null;
                            map.put("message", "上传失败");
                            return map;//上传失败
                        }
                    } else {
                        map.put("message", "第"+i+"个文件上传失败");
                        return map;
                    }
                }
                map.put("listFileName", listFileName);
                map.put("listFilePath", listFilePath);
                map.put("message", "上传成功");
                return map;
         }         
    /**
     * 单个下载
     * @return
     */
    public  Map<String, Object> download(HttpServletResponse response,String fileName,String orderId){
        Map<String, Object> map = new HashMap<String,Object>();
            if (fileName != null) {
                //文件下载路径,应与文件上传路径一致
                String realPath = "upload/"+orderId+"/";
                File file = new File(realPath, fileName);
                if (file.exists()) {
                     try {
                        fileName = new String(fileName.getBytes(),"ISO8859-1");//防止中文名称乱码
                    } catch (UnsupportedEncodingException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } 
                    response.setContentType("application/force-download");// 设置强制下载不打开
                    response.addHeader("Content-Disposition",
                            "attachment;fileName=" +  fileName);// 设置文件名
                    byte[] buffer = new byte[1024];
                    FileInputStream fis = null;
                    BufferedInputStream bis = null;
                    OutputStream os = null;
                    try {
                        fis = new FileInputStream(file);
                        bis = new BufferedInputStream(fis);
                        os = response.getOutputStream();
                        int i = bis.read(buffer);
                        while (i != -1) {
                            os.write(buffer, 0, i);
                            i = bis.read(buffer);
                        }
                        map.put("message", "下载成功");
                    } catch (Exception e) {
                        e.printStackTrace();
                        map.put("message", "下载失败");
                    } finally {
                        if (bis != null) {
                            try {
                                bis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if(os !=null) {
                            try {
                                os.flush();
                                os.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            
                        }
                    }
                }
            }
            return map;
    }
    /**
     * 下载多文件zip压缩文件
     * @param response
     */
    public void FileDownload(HttpServletResponse response) {
//        String realPath = "upload/";
            //需要压缩的文件--包括文件地址和文件名
            String []path ={"D:\\git\\intelligent_audit_system\\intelligent-audit-biz-hospitalization\\upload\\配置.txt",
            "D:\\git\\intelligent_audit_system\\intelligent-audit-biz-hospitalization\\upload\\新建文本文档.txt"};
            // 要生成的压缩文件地址和文件名称
            String desPath = "D:\\DownLoad.zip";
            File zipFile = new File(desPath);
            ZipOutputStream zipStream = null;
            FileInputStream zipSource = null;
            BufferedInputStream bufferStream = null;
            try {
                //构造最终压缩包的输出流
                zipStream = new ZipOutputStream(new FileOutputStream(zipFile));
                for(int i =0;i<path.length;i++){
                    File file = new File(path[i]);
                    //将需要压缩的文件格式化为输入流
                    zipSource = new FileInputStream(file);
                    //压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样
                    ZipEntry zipEntry = new ZipEntry(file.getName());
                    //定位该压缩条目位置,开始写入文件到压缩包中

                    zipStream.putNextEntry(zipEntry);

                    //输入缓冲流
                    bufferStream = new BufferedInputStream(zipSource, 1024 * 10);
                    int read = 0;
                    //创建读写缓冲区
                    byte[] buf = new byte[1024 * 10];
                    while((read = bufferStream.read(buf, 0, 1024 * 10)) != -1)
                    {
                        zipStream.write(buf, 0, read);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //关闭流
                try {
                    if(null != bufferStream) bufferStream.close();
                    if(null != zipStream) zipStream.close();
                    if(null != zipSource) zipSource.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    
    }
    

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值