JAVA 网络资源下载为本地文件并转码Base64 通过restTemplate.postForObject()跨服务转发base64编码转回文件

功能介绍--单位要求网络资源下载到本地以文件进行保存,并通过restTemplate.postForObject()将base64转发到另一个项目的接口中进行base64编码转回文件.之前通过网络资源下载的文件转码后要删除,不占用资源.

import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;
import org.springframework.http.HttpEntity;
import java.io.*;
import java.net.URL;
import java.util.*; 
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.context.config.annotation.RefreshScope;


// 利用uuid命名文件夹名称  实现单用户单文件夹操作  防止多用户访问同一文件夹 因为有删除的操作
//能获取到userid 或者其他唯一值 都可以进行文件夹命名的拼接

@RefreshScope  //实现nacos配置文件热部署 (知识点)

private final static String UUID_PATH = UUID.randomUUID().toString().toUpperCase();

//附件 
List<UpProAttach> listAttac = upproattachdao.selectByPrimaryKey(runnumber);

for (int i = 0; i < listAttac.size(); i++) {
    UpProAttach attacEntity = listAttac.get(i);
    //网络http资源生成文件
    //getFileToBase64() -- 下载得到文件方法  attacEntity.getAttachmentpath()--网络资源路径
    File file = getFileToBase64(attacEntity.getAttachmentpath()); 
    //获取文件名
    String fileName = file.getName();
    //获取文件类型
    String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
    //将生成的文件进行base64编码
    FileInputStream fileInputStream = new FileInputStream(file);
    byte [] bytes = new byte[fileInputStream.available()];
    fileInputStream.read(bytes);
    BASE64Encoder base64Encoder = new BASE64Encoder();
    String encode = base64Encoder.encode(bytes);
    //关闭资源  这一步很重要
    fileInputStream.close();
    //装入实体类
    attacEntity.setAttachmentcontent(encode);
    attacEntity.setAttachmentname(fileName);
    attacEntity.setAttachmenttype(fileType);
    //持久化到数据库
    upproattachdao.updateAttachById(attacEntity);
}

 //删除本地缓存文件
        File file = new File("pic\\cache"+UUID_PATH+"\\");
        deleteFile(file);


    //SecureUtil加密
// 构建
 AES aes = SecureUtil.aes(key.getBytes());  //参数是string
//newAA是一个map  里面装着base64编码数据
 String str = JSON.toJSONStringWithDateFormat(newAA, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteDateUseDateFormat);  

        // 加密为16进制表示
String encryptHex = aes.encryptHex(str);
HttpEntity<String> httpEntity = new HttpEntity<>(encryptHex);
// postUrl //接口请求路径  例如:192.168.0.168:8883/test/testRestTemplate
// httpEntity -- string类型 HttpEntity<String>  值在它的body里
// restTemplate.postForObject  发一条restTemplate请求 (知识点)
JSONObject s = restTemplate.postForObject(postUrl,httpEntity, JSONObject.class);


-------------------------------------------------------------------------------------
/**
     *  删除本地文件夹里的全部文件最后再删除文件夹 
     * @param file
     */
    private void deleteFile(File file) {
        if (file == null || !file.exists()){
            System.out.println("文件删除失败,请检查文件路径是否正确");
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files){
            //打印文件名
            String name = f.getName();
            System.out.println(name);
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()){
                deleteFile(f);
            }else {
                f.delete();
            }
        }
        //删除空文件夹 for循环已经把上一层节点的目录清空。
        file.delete();
    }


-------------------------------------------------------------------------------------

 /**   
     *  File To Base64 -- getFileToBase64方法
     * @param path   SRC网络路径
     * @return
     */
    private File getFileToBase64(String path) {
        File file = null;
        URL urlfile;
        //对本地文件命名,path是http的完整路径,网络资源的名字
        String newUrl = path;
        newUrl = newUrl.split("[?]")[0];
        String[] bb = newUrl.split("/");
        //得到最后一个分隔符后的名字
        String fileName = bb[bb.length - 1];
        //跟随本地项目路径进行保存 -- 实现单人单文件夹操作
        String filePath="pic\\cache"+UUID_PATH+"\\"+fileName;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            //判断文件的父级目录是否存在,不存在则创建
            file = new File(filePath);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            try{
                //创建文件
                file.createNewFile();
            }catch (Exception e){
                e.printStackTrace();
            }
            //下载
            urlfile = new URL(newUrl);
            inputStream = urlfile.openStream();
            outputStream = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }



-------------------------------------------------------------------------------------
 //restTemplate.postForObject 发的请求到此方法 
// 192.168.0.168:8883/test/testRestTemplate

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/rest")
@CrossOrigin
public class TestRestTemplate {

    @PostMapping("/testRestTemplate")
    public JSONObject listExercise(HttpEntity<String> httpEntity ) throws IOException {
        JSONObject jsonObject = new JSONObject();

        String body = httpEntity.getBody();
        AES aes = SecureUtil.aes("A7B46213D59F47DE".getBytes());

        String decryptStr = aes.decryptStr(body, CharsetUtil.CHARSET_UTF_8);
        System.out.println("decryptStr = " + decryptStr);

        //把字符串转回JSONObject格式
        JSONObject jsonObj = JSON.parseObject(decryptStr);

        List<Map> list = (List<Map>) jsonObj.get("attach");

        for (int i = 0; i < list.size(); i++) {
            Map<String,String> map1 = list.get(i);
            String name1 = map1.get("attachmentname");
            String base641 =  map1.get("attachmentcontent");

            //重点    
            //base64编码转回文件
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes1 = decoder.decodeBuffer(base641);
            // 创建一个 空的文件写到 这个新的文件中去
            //"E:/base64pic/aa.jpg"  路径可以自定义  也可以生成在项目所在文件夹里
            // String filePath="pic\\cache"+UUID_PATH+"\\"+fileName;  项目所在文件夹
            String fileName = name1;
            File aa2 = new File("E:/base64pic/" + fileName);
            if(!aa2.getParentFile().exists()){
                aa2.getParentFile().mkdirs();
            }
            //这步极为重要---createNewFile() 创建文件 否则新建的都是文件夹
            aa2.createNewFile();

            FileOutputStream fileOutputStream = new FileOutputStream(aa2);
            fileOutputStream.write(bytes1);
            fileOutputStream.flush();
            fileOutputStream.close();
        }



        jsonObject.put("code","200");

        return jsonObject;
    }


}
     


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值