java实现本地与服务器之间文件的上传与下载

从本地上传的到服务器

   /**
     * 上传文件到指定目录
     * @param filePath 服务器路径
     * @param file 本地文件
     * @return
     */

 public static int uploadFile(String filePath,MultipartFile file){
        File desFile = new File(filePath);
        if(!desFile.getParentFile().exists()){
            desFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(desFile);
        } catch (IllegalStateException | IOException e) {
            logger.info("子文件上传失败!");
            e.printStackTrace();
            return 1;
        }
        return 0;
    }

从服务器下载到本地

    /**
     * 文件下载
     * @param path 服务器上的文件路径
     * @param response
     * @return
     */
    public static int downloadFile(String path, HttpServletResponse response) {
        int result = 1;
        InputStream is = null;
        OutputStream os = null;
        try {
            File file = new File(path);
            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "utf-8"));
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            is = new FileInputStream(file);
            os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = is.read(b)) > 0) {
                os.write(b, 0, length);
            }
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            result = 0;
        } finally {
            closeInputStream(is);
            closeOutputStream(os);
        }

        return result;
    }

下面是两个关流的方法

    private static void closeInputStream(InputStream is) {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void closeOutputStream(OutputStream os) {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值