栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java上传下载文件并实现加密解密

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java上传下载文件并实现加密解密

使用 Jersey 服务器实现上传,使用 HTTP 请求实现下载

引入依赖

在 pom.xml 中添加 Jersey 相关依赖


  com.sun.jersey
  jersey-client
  1.18.1

创建工具类

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class FileUtils {

  // 加密/解密文件的密钥
  public static final int CRYPTO_SECRET_KEY = 0x99;

  public static int FILE_DATA = 0;

  
  public static void cryptoFile(File srcFile, File encFile) throws Exception {

    InputStream inputStream = new FileInputStream(srcFile);
    OutputStream outputStream = new FileOutputStream(encFile);
    while ((FILE_DATA = inputStream.read()) > -1) {
      outputStream.write(FILE_DATA ^ CRYPTO_SECRET_KEY);
    }
    inputStream.close();
    outputStream.flush();
    outputStream.close();
  }

  
  public static File multipartFileToFile(MultipartFile multipartFile, String tempFilePath) {

    File file = new File(tempFilePath);
    // 获取文件原名
    String originalFilename = multipartFile.getOriginalFilename();
    // 获取文件后缀
    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
    if (!file.exists()) {
      file.mkdirs();
    }
    // 创建临时文件
    File tempFile = new File(tempFilePath + "\" + UUID.randomUUID().toString().replaceAll("-", "") + suffix);
    try {
      if (!tempFile.exists()) {
 // 写入临时文件
 multipartFile.transferTo(tempFile);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return tempFile;
  }

  
  public static String uploadByJersey(String fileServerPath, String folderPath, File uploadFile, boolean isCrypto) {

    String suffix = uploadFile.getName().substring(uploadFile.getName().lastIndexOf("."));
    String randomFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
    String fullPath = fileServerPath + folderPath + "/" + randomFileName;
    try {
      if (isCrypto) {
 // 创建加密文件
 File cryptoFile = new File(uploadFile.getPath().substring(0, uploadFile.getPath().lastIndexOf(".")) + "crypto" + uploadFile.getPath().substring(uploadFile.getPath().lastIndexOf(".")));
 // 执行加密
 cryptoFile(uploadFile, cryptoFile);
 // 保存加密后的文件
 uploadFile = cryptoFile;
      }
      // 创建 Jersey 服务器
      Client client = Client.create();
      WebResource wr = client.resource(fullPath);
      // 上传文件
      wr.put(String.class, fileToByte(uploadFile));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return fullPath;
  }

  
  public static File downloadByURL(String url, String filePath, String fileName, boolean isCrypto) {

    File file = new File(filePath);
    if (!file.exists()) {
      file.mkdirs();
    }
    FileOutputStream fileOut;
    HttpURLConnection httpURLConnection;
    InputStream inputStream;
    try {
      URL httpUrl = new URL(url);
      httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
      httpURLConnection.setDoInput(true);
      httpURLConnection.setDoOutput(true);
      httpURLConnection.setUseCaches(false);
      httpURLConnection.connect();
      inputStream = httpURLConnection.getInputStream();
      BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
      if (!filePath.endsWith("\")) {
 filePath += "\";
      }
      file = new File(filePath + fileName);
      fileOut = new FileOutputStream(file);
      BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOut);
      byte[] bytes = new byte[4096];
      int length = bufferedInputStream.read(bytes);
      //保存文件
      while (length != -1) {
 bufferedOutputStream.write(bytes, 0, length);
 length = bufferedInputStream.read(bytes);
      }
      bufferedOutputStream.close();
      bufferedInputStream.close();
      httpURLConnection.disconnect();
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (isCrypto) {
      try {
 // 创建解密文件
 File cryptoFile = new File(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext().getRealPath("/") + "\temp\" + UUID.randomUUID().toString().replaceAll("-", "") + file.getName().substring(file.getName().lastIndexOf(".")));
 // 执行解密
 cryptoFile(file, cryptoFile);
 // 删除下载的原文件
 file.delete();
 // 保存解密后的文件
 file = cryptoFile;
      } catch (Exception e) {
 e.printStackTrace();
      }
    }
    return file;
  }

  
  public static boolean deleteByJersey(String url) {

    try {
      Client client = new Client();
      WebResource webResource = client.resource(url);
      webResource.delete();
      return true;
    } catch (UniformInterfaceException e) {
      e.printStackTrace();
    } catch (ClientHandlerException e) {
      e.printStackTrace();
    }
    return false;
  }

  
  public static byte[] fileToByte(File file) {

    byte[] buffer = null;
    try {
      FileInputStream fileInputStream = new FileInputStream(file);
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      byte[] bytes = new byte[1024];
      int n;
      while ((n = fileInputStream.read(bytes)) != -1) {
 byteArrayOutputStream.write(bytes, 0, n);
      }
      fileInputStream.close();
      byteArrayOutputStream.close();
      buffer = byteArrayOutputStream.toByteArray();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return buffer;
  }
}

测试上传


@Test
public String upload(MultipartFile multipartFile, boolean isCrypto) {

  HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  // 生成临时文件
  File tempFile = FileUtil.multipartFileToFile(multipartFile, request.getServletContext().getRealPath("/") + "\static\temp");
  // 上传文件并返回文件路径
  String uploadFilePath = FileUtil.uploadByJersey("http://localhost:8080", "/upload", tempFile, isCrypto);
  if (uploadFilePath != null) {
    return "上传成功";
  }
  else {
    return "上传失败";
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/134512.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号