java学习之对ftpurl文件进行下载上传至服务器

最近公司调用摄像头设备的SDK,API返回的是照片的ftpurl,我需要把这些图片储存下来放在数据库和云服务器中,所以我上网搜了下相关的资料,决定先把图片先编码为Base64,下面就是我的代码:

//先在pom文件中引入依赖
 <dependency>
     <groupId>commons-codec</groupId>
     <artifactId>commons-codec</artifactId>
     <version>1.10</ve	rsion>
</dependency>

我使用的是org.apache.commons.codec.binary.Base64中的Base64.encodeBase64String(),这个和sun公司的sun.misc.BASE64Encoder类,因为当你将编码后的字符串输出后会发现字符串中存在换行符 (\r\n) 原来“回车换行符(\r\n)”是在Windows才有,而Linux只有换行(\n),Mac只有回车(\r)所以我就使用了org.apache.commons.codec.binary.Base64,还有就是JDK8的java.util.Base64这个性能也不错。

import org.apache.commons.codec.binary.Base64;
public static  String GetImageStr(String imgFilePath) {
        // 将ftpurl中的图片文件转化为字节数组字符串,并对其进行Base64编码处理
        byte[] b = null;
        try {
            URL url = new URL(imgFilePath);
            URLConnection urlConnection = url.openConnection();
            InputStream in1 = urlConnection.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int n = 0;
            while (-1 != (n = in1.read(buffer))) {
                output.write(buffer, 0, n);
            }
            b =   output.toByteArray();
            in1.read(b);
            in1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        String base64 = Base64.encodeBase64String(b);
        log.debug("base64 = {}",base64);
        return base64;
        // 返回Base64编码过的字节数组字符串    }
    }

但是由于编码后的Base64长度太长,虽然数据库存的下,但也要设置varchar到90000长度,而且最重要的是把图片的Base64传给前端后,前端不好处理,而且非常影响性能,而且还会导致服务器内存溢出,这是个很严重的问题。于是我想到了先把图片存进数据库中,然后再把存进数据库中的图片的url发送给前端。

	
    //MultipartFile需要引入的依赖是
	   <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
	/*
    * 这个需要引入的依赖是
    * 
    * 这里我先把base64图片转换成MultipartFile文件
    */
    public  static MultipartFile base64MutipartFile(String imgStr){
        try {
            String [] baseStr = imgStr.split(",");
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] b =  new byte[0];
            b = base64Decoder.decodeBuffer(baseStr[1]);
            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return  new BASE64DecodedMultipartFile(b,baseStr[0]) ;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    /*
    * 再把MultipartFile文件发送给服务器
    */
    public static String getPicture(MultipartFile file_data) throws IOException {
        String access_url = "服务器ip:端口号";
        String filePath = "/data/capture/";
        if (file_data.isEmpty()) {
            log.error("文件为空!");
            return "文件为空!";
        }
        // 获取文件名
        String fileName = file_data.getOriginalFilename();
        log.debug("------文件名为:" + fileName);
        // 获取文件的后缀名
        if (fileName != null){
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.debug("------后缀名为:" + suffixName);
        }
        log.debug("------filePath + fileName = {}", filePath + fileName);
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            boolean res = dest.getParentFile().mkdirs();
            log.debug("------创建目录res:{}", res);
        }
        try {
            file_data.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return fileName;
        //这里返回的就是服务器中的图片名称
       //如果你要返回图片url就要加上 return "服务器ip:端口号/存放图片文件夹路径"+fileName
    }
package com.kwantler.YN_EW.service.impl; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class FilePhoto { /** * 从网络Url下载文件 * * @param urlStr * @param fileName * @param savePath * @throws IOException */ public static void downLoadByUrl(String urlStr, String fileName, String savePath) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置超时间为3秒 conn.setConnectTimeout(5 * 1000); // 防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // 得到输入流 InputStream inputStream = conn.getInputStream(); // 获取自己数组 byte[] getData = readInputStream(inputStream); // 文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdir(); } File file = new File(saveDir + File.separator + fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } System.out.println("info:" + url + " download success"); } /** * 从输入流中获取字节数组 * * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } public static void main(String[] args) { try { downLoadByUrl( "https://www.mybiosource.com/images/tds/protocol_samples/MBS700_Antibody_Set_Sandwich_ELISA_Protocol.pdf", "ELISA.pdf", "E:/upload/protocol"); } catch (Exception e) { // TODO: handle exception } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值