欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 上传和下载文件(附加密和解密)

程序员文章站 2022-06-27 21:38:01
使用 服务器实现上传,使用 请求实现下载 引入依赖 在 中添加 相关依赖 创建工具类 测试上传 文章作者:彭超 本文首发于个人博客: "https://antoniopeng.com/2019/04/09/java/Java%E4%B8%8A%E4%BC%A0%E5%92%8C%E4%B8%8B%E ......

使用 jersey 服务器实现上传,使用 http 请求实现下载

引入依赖

pom.xml 中添加 jersey 相关依赖

<dependency>
    <groupid>com.sun.jersey</groupid>
    <artifactid>jersey-client</artifactid>
    <version>1.18.1</version>
</dependency>

创建工具类

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 "上传失败";
    }
}