Java 中使用 Jersey 实现上传文件(附加密和解密)

Java 中使用 Jersey 实现上传文件(附加密和解密)Jersey简介Jersey是开源的RESTful框架,实现了JAX-RS规范,提供了更多的特性和工具,可以进一步地简化RESTfulservice和client开发,与S

大家好,又见面了,我是你们的朋友全栈君。

Jersey 简介


Jersey 是开源的 RESTful 框架,实现了 JAX-RS 规范,提供了更多的特性和工具, 可以进一步地简化 RESTful service 和 client 开发,与 Struts 类似,它同样可以和 Hibernate、Spring 框架整合。此处使用它实现文件上传功能。

引入依赖


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

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.18.1</version>
</dependency>

然后创建一个名为 FileUtils 的文件工具类。

生成临时文件方法


/**
   * MultipartFile 生成临时文件
   * @param multipartFile
   * @param tempFilePath 临时文件路径
   * @return File 临时文件
*/
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 final int CRYPTO_SECRET_KEY = 0x99;

/**
   * 加密/解密文件
   * @param srcFile 原文件
   * @param encFile 加密/解密后的文件
   * @return 加密/解密后的文件
   * @throws Exception
*/
public static File 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();
    return encFile;
}

上传文件方法


/**
   * 上传文件
   * @param fileServerPath	文件服务器地址
   * @param folderPath    存放的文件夹路径(比如存放在文件服务器的 upload 文件夹下,即 ”/upload“)
   * @param uploadFile	需要上传的文件
   * @param isCrypto	是否加密
   * @return String	文件上传后的全路径
*/
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(".")));
            // 执行加密并覆盖原文件
            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;
}

下载文件方法


/**
   * 下载文件
   * @param url   文件路径
   * @param filePath  文件保存路径
   * @param fileName  文件名称(包含文件后缀)
   * @param isCrypto  是否解密
   * @return File
*/
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;
}

删除文件方法


/**
   * 删除文件服务器上的文件
   * @param url 文件路径
   * @return boolean
*/
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;
}

完整工具类


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;

    /**
     * 加密/解密 文件
     * @param srcFile 原文件
     * @param encFile 加密/解密后的文件
     * @throws Exception
     */
    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();
    }

    /**
     * MultipartFile 生成临时文件
     * @param multipartFile
     * @param tempFilePath 临时文件路径
     * @return File 临时文件
     */
    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;
    }

    /**
     * 上传文件
     * @param fileServerPath	文件服务器地址
     * @param folderPath    存放的文件夹路径(比如存放在文件服务器的 upload 文件夹下,即 ”/upload“)
     * @param uploadFile	需要上传的文件
     * @param isCrypto	是否加密
     * @return String	文件上传后的全路径
     */
    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;
    }

    /**
     * 下载文件
     * @param url   文件路径
     * @param filePath  文件保存路径
     * @param fileName	文件名称(包含文件后缀)
     * @param isCrypto  是否解密
     * @return File
     */
    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;
    }

    /**
     * 删除文件服务器上的文件
     * @param url 文件路径
     * @return boolean
     */
    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;
    }

    /**
     * File转Bytes
     * @param file
     * @return byte[]
     */
    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;
    }
}

测试上传


/**
 * @param multipartFile 上传文件
 * @param isCrypto 是否加密文件
 * @return
 */
@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 "上传失败";
    }
}

更多干货请移步:https://antoniopeng.com
更多干货请移步:https://antoniopeng.com

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/154264.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • 云服务是免费的吗_云服务器收费

    云服务是免费的吗_云服务器收费近年来,云服务器的普及率快速上升,相当一部分企业从传统服务器转向云服务器,而随着市场的发展,云服务器供应商尤其多,服务器供应商竞争日趋激烈。此时不少服务商表示自己推出永久免费使用的云服务器,面对这样的消息不少企业会感到疑惑,永久免费使用的云服务器究竟是否可信?那么下面就由摩杜云小杜和大家讲一讲有没有永久免费的云服务器。一、首先市场上根本就没有所谓的永久免费使用的云服务器虽然现如今云技术发展快速,但是云资源的成本还是很高的,所以商家为了自己获益,不可能会提供免费的云主机租用服务。但是目前市场上有服务商提供

    2022年10月6日
  • Opencv学习笔记(六)SURF学习笔记

    Opencv学习笔记(六)SURF学习笔记

    2021年12月15日
  • java中sqrt函数的详解[通俗易懂]

    java中sqrt函数的详解[通俗易懂]一、原理:牛顿迭代法具体解释:牛顿迭代法求平方根那我们怎么用牛顿迭代法呢?首先要明白,牛顿迭代法求的是函数和X轴的交点的横坐标,也就是我们说的根1)那么第一步就是构建曲线了。假设有一个数c,我们求它的平方根x,那么有一个等式,x^2=c;挪到一边就是求f= x^2-c的根x2)带入上面的公式也就是 3)既然是个迭代,那么

    2022年5月7日
  • Scala_scala定义变量

    Scala_scala定义变量scala中print是直接输出print(s”$a”)输出为变量的值println()打印时自动换行println()相当于print(+’\n’)objectTestScala{defmain(args:Array[String]):Unit={println(“HelloScala!!”)vala1=’T’vararr=…

    2022年9月27日
  • 【13】进大厂必须掌握的面试题-配置管理面试

    点击上方“全栈程序员社区”,星标公众号 重磅干货,第一时间送达 Q1。配置管理流程的目标是什么? 配置管理(CM)的目的是通过使开发或部署过程可控和可重复,从而创建更高质量的产品或…

    2021年6月23日
  • JAVA基础——接口(全网最详细教程)「建议收藏」

    JAVA基础——接口(全网最详细教程)「建议收藏」Java基础——接口接口概念官方解释:Java接口是一系列方法的声明,是一些方法特征的集合,一个接口只有方法的特征没有方法的实现,因此这些方法可以在不同的地方被不同的类实现,而这些实现可以具有不同的行为(功能)。我的解释:接口可以理解为一种特殊的类,里面全部是由全局常量和公共的抽象方法所组…

    2022年6月5日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号