java 文件上传下载删除

版权声明:[ws - 兮的博客] - 空间专属,未经声明不得私自转载 https://blog.csdn.net/qq_41463655/article/details/83987985

适用于springboot,ssm框架等

    //  ============文件删除===============
    @RequestMapping(value = "/deleteFile", method = RequestMethod.GET)
    @ResponseBody
    public void deleteFile(Long fileId) {
        File fileVal = fileService.selectId(fileId);
        fileService.deleteId(fileId); //删除数据库
        java.io.File file = new java.io.File(fileVal.getUrl());
        boolean exis = file.exists();     // 判断目录或文件是否存在
        boolean isex = file.isFile();     // 判断是否为文件
        file.delete();  //删除文件
    }

上传文件方法,适用于多,单文件上传

    //  ============controller方法===============
    @RequestMapping(value = "/fileUpdateImg", method = RequestMethod.POST)
    @ResponseBody
    public String handleFileUpload1(HttpServletRequest request) throws IOException {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");  //接收到的文件
        String filePath = "file/img/";      //上传路径
        List<Map<String, String>> list = utlisFile.handleFileUpload(files, filePath);      //文件上传
        return "yes";
    }

    //  ============工具类( utlisFile ) 方法===============
  /* *
     * @Description //TODO 文件上传
     * @Date  2018/10/8/008/
     * @Param [files, filepath]
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.String>>
     **/
    public static List<Map<String, String>> handleFileUpload(List<MultipartFile> files, String filepath) throws IOException {
        List<Map<String, String>> listfile = new ArrayList();
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    //上传路径
                    String uploadFilePath = file.getOriginalFilename();
                    String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf('\\') + 1,uploadFilePath.indexOf('.'));
                    String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
                    //获取跟目录
                    File path = new File(ResourceUtils.getURL("classpath:").getPath());
                    if (!path.exists()) path = new File("");
                     File upload = new File(path.getAbsolutePath(), filepath);
                    if (!upload.exists()) upload.mkdirs();
                    System.out.println(upload);
                    String datess = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                    String pathfile = upload + "\\" + uploadFileName + datess + "." + uploadFileSuffix;
                    System.out.println(pathfile);
                    stream = new BufferedOutputStream(new FileOutputStream(new File(pathfile)));
                   stream = new BufferedOutputStream(new FileOutputStream(new File(pathfile)));
                    byte[] bytes = file.getBytes();
                    stream.write(bytes, 0, bytes.length);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (stream != null) {
                        stream.close();
                    }
                }
            }
        }
        return listfile;
    }

文件下载,自行传文件路径,工具类 utlisFile 方法

   /**
     * @return
     * @Description //TODO 文件下载
     * @Date 2018/10/8/008/
     * @Param
     **/
    public static void excelxiazan(HttpServletResponse res, String fileName) throws
            UnsupportedEncodingException {
        //要下载的文件路径(前台传id)
        //String fileName = excelService.selectbyId(eid);
        //文件命名(获得完整路径最后的 \\ 后的内容)
        int fileXs = fileName.lastIndexOf("\\");
        //下载文件名,去掉时时间戳
        String fileXsl = fileName.substring(fileXs + 1, fileName.length() - 18);
        //String fileXsl = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        //信息头: 会告诉浏览器这个文件的名字和类型(必须设置)
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        //Content-Disposition : 指定的类型是文件的扩展名(也就是下载文件的名字)
        //下载名乱码解决  -->  java.net.URLEncoder.encode(fileXsl, "UTF-8")
        res.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileXsl + ".xls", "UTF-8"));
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

多文件压缩下载

    //========================== TODO (方法)多文件下载ZIP包 ========================
    /* *
     * 需要 filePaths 下载路径集
     *      zipNamex  压缩包名+ .zip
     *      res       HttpServletResponse
     **/
    public void exceDownload(List<String> filePaths, HttpServletResponse res, String zipNamex) throws
            IOException {
        String zipName = zipNamex;                                                          //压缩包名字
        res.setContentType("text/html; charset=UTF-8"); //设置编码字符
        res.setContentType("application/octet-stream"); //设置内容类型为下载类型
        OutputStream out = res.getOutputStream();          //创建页面返回方式为输出流,会自动弹出下载框
        File path = new File(ResourceUtils.getURL("classpath:").getPath());   //项目跟目录
        if (!path.exists()) path = new File("");
        File upload = new File(path.getAbsolutePath(), "static/images/uploaZip");     //压缩包根目录
        if (!upload.exists()) upload.mkdirs();
        String zipFilePath = upload + File.separator + zipName;                               //拼接目录
        //创建zip文件输出流 == 压缩文件========================================================
        File zip = new File(zipFilePath);
        if (!zip.exists()) {
            zip.createNewFile();
        }
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip));
        //打压缩包
        this.zipFile(String.valueOf(upload), zipName, zipFilePath, filePaths, zos);
        zos.close();                                                                         //设置下载的压缩文件名称
        res.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(zipName, "UTF-8"));
        //创建zip文件输出流==========================================================
        //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath));
        byte[] buff = new byte[bis.available()];
        bis.read(buff);
        bis.close();
        out.write(buff);//输出数据文件
        out.flush();//释放缓存
        out.close();//关闭输出流
    }

    /**
     * //TODO  压缩文件
     *
     * @param zipBasePath 临时压缩文件基础路径
     * @param zipName     临时压缩文件名称
     * @param zipFilePath 临时压缩文件完整路径
     * @param filePaths   需要压缩的文件路径集合
     * @throws IOException
     */
    public static String zipFile(String zipBasePath, String zipName, String
            zipFilePath, List<String> filePaths, ZipOutputStream zos) throws IOException {
        //循环读取文件路径集合,获取每一个文件的路径
        for (String filePath : filePaths) {
            File inputFile = new File(filePath);  //根据文件路径创建文件
            if (inputFile.exists()) { //判断文件是否存在
                if (inputFile.isFile()) {  //判断是否属于文件,还是文件夹
                    //创建输入流读取文件
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
                    //将文件写入zip内,即将文件进行打包
                    zos.putNextEntry(new ZipEntry(inputFile.getName()));

                    //写入文件的方法,同上
                    int size = 0;
                    byte[] buffer = new byte[1024];  //设置读取数据缓存大小
                    while ((size = bis.read(buffer)) > 0) {
                        zos.write(buffer, 0, size);
                    }
                    //关闭输入输出流
                    zos.closeEntry();
                    bis.close();

                } else {  //如果是文件夹,则使用穷举的方法获取文件,写入zip
                    try {
                        File[] files = inputFile.listFiles();
                        List<String> filePathsTem = new ArrayList<String>();
                        for (File fileTem : files) {
                            filePathsTem.add(fileTem.toString());
                        }
                        return zipFile(zipBasePath, zipName, zipFilePath, filePathsTem, zos);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

单文件上传

  /*==========================  单文件上传 =============================== */
    @ResponseBody
    @RequestMapping(value = "/testUploadFile", method = RequestMethod.POST)
    public String testUploadFile(HttpServletRequest req,
                                 MultipartHttpServletRequest multiReq) {
        // 获取上传文件的路径
        String uploadFilePath = multiReq.getFile("file").getOriginalFilename();
        System.out.println("uploadFlePath:" + uploadFilePath);
        // 截取上传文件的文件名
        String uploadFileName = uploadFilePath.substring(
                uploadFilePath.lastIndexOf('\\') + 1, uploadFilePath.indexOf('.'));
        System.out.println("multiReq.getFile()" + uploadFileName);
        // 截取上传文件的后缀
        String uploadFileSuffix = uploadFilePath.substring(
                uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
        System.out.println("uploadFileSuffix:" + uploadFileSuffix);
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fis = (FileInputStream) multiReq.getFile("file").getInputStream();
            //获取跟目录
            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists()) path = new File("");
            System.out.println("path:" + path.getAbsolutePath());
            //如果上传目录为/static/images/upload/,则可以如下获取:
            File upload = new File(path.getAbsolutePath(), "static/images/upload/");
            if (!upload.exists()) upload.mkdirs();
            System.out.println("upload url:" + upload.getAbsolutePath());
            //在开发测试模式时,得到的地址为:{项目跟目录}/target/static/images/upload/
            //在打包成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/
            fos = new FileOutputStream(upload + "/" + uploadFileName + "." + uploadFileSuffix);
            byte[] temp = new byte[1024];
            int i = fis.read(temp);
            while (i != -1) {
                fos.write(temp, 0, temp.length);
                fos.flush();
                i = fis.read(temp);
            }
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "上传失败";
    }

猜你喜欢

转载自blog.csdn.net/qq_41463655/article/details/83987985