JRT文件服务实现

2023-12-14 10:35:05

网站与客户端打印和导出方面已经无大碍了,今天抽时间整整文件服务,文件服务设计可以查看下面连接。原理一样,代码会有些变化。
文件服务设计

在这里插入图片描述

在这里插入图片描述

首先实现文件服务的服务端,就是一个业务脚本,用来接收上传、移动和删除文件请求,老的是Webservice:

import JRT.Core.MultiPlatform.JRTContext;
import JRT.Core.Util.ReflectUtil;
import JRTBLLBase.BaseHttpHandlerNoSession;
import JRTBLLBase.Helper;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * 上传文件服务,文件服务地址配站点的相对对象到/FileService
 */
public class JRTUpFileService extends BaseHttpHandlerNoSession {
    /**
     * 上传文件
     * fileBase64Str 文件的Base64串
     * fileName 文件名称
     * remotePath 相对路径,基于网站根目录下的FileService文件夹
     *
     * @return
     */
    public String Upload() {
        String fileBase64Str = Helper.ValidParam(JRTContext.GetRequest(Request, "fileBase64Str"), "");
        String fileName = Helper.ValidParam(JRTContext.GetRequest(Request, "fileName"), "");
        String remotePath = Helper.ValidParam(JRTContext.GetRequest(Request, "remotePath"), "");
        try {
            //根路径
            String rootPath = Paths.get(JRTContext.WebBasePath, "FileService").toString();
            File dir = new File(rootPath);
            //创建根目录
            if (!dir.exists()) {
                dir.mkdir();
            }
            //目录不存在就创建
            String pathAdd = rootPath;
            if (remotePath != "") {
                String[] remoteArr = remotePath.split("/");
                for (int i = 0; i < remoteArr.length; i++) {
                    if (remoteArr[i] == "") {
                        continue;
                    }
                    pathAdd = Paths.get(pathAdd, remoteArr[i]).toString();
                    String curPath = pathAdd;
                    File dirCur = new File(curPath);
                    //创建根目录
                    if (!dirCur.exists()) {
                        dirCur.mkdir();
                    }
                }
            }
            pathAdd = Paths.get(pathAdd, fileName).toString();
            //文件保存全路径
            String fileFullName = pathAdd;
            byte[] arr = Base64.getDecoder().decode(fileBase64Str);
            File fileSave = new File(fileFullName);
            if (fileSave.exists()) {
                fileSave.delete();
            }
            Files.write(Paths.get(fileFullName), arr, StandardOpenOption.CREATE_NEW);
            //返回结果
            return "";
        } catch (Exception ex) {
            System.out.println("保存异常:" + ex.getMessage());
            return ex.getMessage();
        }
    }


    /**
     * 移动文件
     * currentFilename 当前全路径
     * newFilename 新的全路径
     *
     * @return
     */
    public String ReName() {
        String currentFilename = Helper.ValidParam(JRTContext.GetRequest(Request, "currentFilename"), "");
        String newFilename = Helper.ValidParam(JRTContext.GetRequest(Request, "newFilename"), "");
        try {
            currentFilename = currentFilename.replace('\\', '/');
            newFilename = newFilename.replace('\\', '/');
            //根路径
            String rootPath = Paths.get(JRTContext.WebBasePath, "FileService").toString();
            currentFilename = currentFilename.replace("/FileService", "" + (char) 0);
            currentFilename = currentFilename.split((char) 0 + "")[1];
            String[] curArr = currentFilename.split("/");
            currentFilename = Combine(curArr);
            newFilename = newFilename.replace("/FileService", "" + (char) 0);
            newFilename = newFilename.split((char) 0 + "")[1];
            String[] newArr = newFilename.split("/");
            newFilename = Combine(newArr);

            String curFileFullName = Paths.get(rootPath, currentFilename).toString();
            String newFileFullName = Paths.get(rootPath, newFilename).toString();
            //尝试创建目录
            List<String> remoteAddList = new ArrayList<>();
            remoteAddList.add(rootPath);
            if (newFilename != "") {
                for (int i = 0; i < newArr.length - 1; i++) {
                    if (newArr[i] == "") {
                        continue;
                    }
                    remoteAddList.add(newArr[i]);
                    String curPath = Combine(remoteAddList);
                    File dirCur = new File(curPath);
                    //创建根目录
                    if (!dirCur.exists()) {
                        dirCur.mkdir();
                    }
                }
            }
            File fileMove = new File(curFileFullName);
            if (fileMove.exists()) {
                Files.move(Paths.get(curFileFullName), Paths.get(newFileFullName));
            } else {
                return "源文件不存在!" + curFileFullName;
            }
            //返回结果
            return "";
        } catch (Exception ex) {
            return ex.getMessage();
        }
    }

    /**
     * 删除文件
     * fileName:全路径
     *
     * @return
     */
    public String Delete() {
        String fileName = Helper.ValidParam(JRTContext.GetRequest(Request, "fileName"), "");
        try {
            fileName = fileName.replace('\\', '/');
            //根路径
            String rootPath = Paths.get(JRTContext.WebBasePath, "FileService").toString();
            fileName = fileName.replace("/FileService", "" + (char) 0);
            fileName = fileName.split((char) 0 + "")[1];
            String[] curArr = fileName.split("/");
            fileName = Combine(curArr);
            String curFileFullName = Paths.get(rootPath, fileName).toString();
            File fileDel = new File(curFileFullName);
            if (fileDel.exists()) {
                fileDel.delete();
            } else {
                return "删除文件不存在!" + curFileFullName;
            }
            //返回结果
            return "";
        } catch (Exception ex) {
            return ex.getMessage();
        }
    }

    /**
     * 合并路径
     *
     * @param arr
     * @return
     */
    private String Combine(String[] arr) {
        //获取系统路径分隔符
        String pathSeparator = System.getProperty("file.separator");
        // 使用 String.join() 方法将路径组件合并成一个路径字符串
        String pathString = String.join(pathSeparator, arr);
        return pathString;
    }

    /**
     * 合并路径
     *
     * @param arr
     * @return
     */
    private String Combine(List<String> arr) {
        //获取系统路径分隔符
        String pathSeparator = System.getProperty("file.separator");
        // 使用 String.join() 方法将路径组件合并成一个路径字符串
        String pathString = String.join(pathSeparator, arr);
        return pathString;
    }
}

对网站上传文件进行包装,抽取出FileCollection来表示页面提交的文件:

package JRT.Core.MultiPlatform;

import jakarta.servlet.http.Part;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileCollection
{
    /**
     * 存上传的文件对象
     */
    private Part file = null;

    /**
     * 上传文件对象初始化
     * @param part
     */
    public void InnerInit(Part part)
    {
        this.file = part;
    }

    /**
     * 获取文件名
     * @return
     * @throws Exception
     */
    public String GetFileName() throws Exception
    {
        if (file == null)
        {
            throw new Exception("未初始化文件对象!");
        }
        return file.getSubmittedFileName();
    }

    /**
     * 获取文件大小
     * @return
     * @throws Exception
     */
    public int GetLength() throws Exception
    {
        if (file == null)
        {
            throw new Exception("未初始化文件对象!");
        }
        return (int)file.getSize();
    }

    public InputStream GetInputStream() throws Exception
    {
        if (file == null)
        {
            throw new Exception("未初始化文件对象!");
        }
        return file.getInputStream();
    }

    /**
     * 保存文件到指定路径,绝对路径
     * @param abpath 保存文件的绝对路径,不可空
     * @param filename 新保存的文件名,如果为空则按原文件名保存
     * @throws Exception
     */
    public void Save2File(String abpath, String filename) throws Exception
    {
        if (abpath == null || abpath.isEmpty())
        {
            throw new Exception("需要传入保存文件的绝对目录");
        }
        Path filepath = Paths.get(abpath);
        //目录不存在的话就循环创建
        if (!filepath.toFile().exists())
        {
            String[] paths = abpath.replace("\\","/").split("/");
            Path allpath = null;
            for (var path : paths) {
                if (path.isEmpty()) continue;
                if (allpath == null) {
                    //Linux路径以/开始,所有补上
                    if (abpath.startsWith("/"))
                    {
                        allpath = Paths.get("/", path);
                    }
                    else
                    {
                        allpath = Paths.get(path);
                    }
                } else {
                    allpath = Paths.get(allpath.toString(), path);
                }
                //是目录,并且已经存在就不处理
                if (!allpath.toFile().exists())
                {
                    Files.createDirectory(allpath);
                }

            }
        }
        //如果不传入文件的话就以源文件名保存
        if (filename == null || filename.isEmpty())
        {
            filename = this.GetFileName();
        }
        File file = Paths.get(abpath, filename).toFile();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        this.GetInputStream().transferTo(fileOutputStream);
        fileOutputStream.flush();
        //释放资源
        fileOutputStream.close();
        this.GetInputStream().close();
    }

    /**
     * 保存文件到指定文件,文件可以不用先创建
     * @param filename 新保存的文件名
     * @throws Exception
     */
    public void Save2File(String filename) throws Exception
    {
        if (filename == null || filename.isEmpty())
        {
            throw new Exception("需要传入保存文件的绝对路径!");
        }
        Path filepath = Paths.get(filename);
        //目录不存在的话就循环创建
        if (!filepath.toFile().exists())
        {
            String[] paths = filename.replace("\\","/").split("/");
            Path allpath = null;
            for (int i = 0; i < paths.length - 1; i++)
            {
                String path = paths[i];
                if (path.isEmpty()) continue;
                if (allpath == null)
                {
                    //Linux路径以/开始,所有补上
                    if (filename.startsWith("/"))
                    {
                        allpath = Paths.get("/", path);
                    }
                    else
                    {
                        allpath = Paths.get(path);
                    }
                }
                else
                {
                    allpath = Paths.get(allpath.toString(), path);
                }
                //是目录,并且已经存在就不处理
                if (allpath.toFile().exists()) continue;
                Files.createDirectory(allpath);
            }
            //传入的最后一个路径为文件名
            allpath = Paths.get(allpath.toString(), paths[paths.length - 1]);
            if(!allpath.toFile().exists())
            {
                Files.createFile(allpath);
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(filename);
        this.GetInputStream().transferTo(fileOutputStream);
        fileOutputStream.flush();
        //释放资源
        fileOutputStream.close();
        this.GetInputStream().close();
    }


    /**
     * 保存文件到默认路径
     * @throws Exception
     */
    public void Save2File() throws Exception
    {
        String basepath = JRT.Core.MultiPlatform.JRTContext.WebBasePath;
        Path path = Paths.get(basepath, "FileService");
        if (!path.toFile().exists())
        {
            Files.createDirectory(path);
        }
        Path file = Paths.get(path.toString(), this.GetFileName());
        FileOutputStream fileOutputStream = new FileOutputStream(file.toFile());
        this.GetInputStream().transferTo(fileOutputStream);
        fileOutputStream.flush();
        //释放资源
        fileOutputStream.close();
        this.GetInputStream().close();
    }
}

对获取前端提交文件包装,方便统一拦截上传类型等

package JRT.Core.MultiPlatform;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.Part;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import JRT.Core.MultiPlatform.FileCollection;

public class JRTWebFile
{
    /**
     * 获取http请求的文件流信息
     * @param request
     * @return
     */
    public static List<FileCollection> GetFiles(HttpServletRequest request)
    {
        List<FileCollection> fileList = new ArrayList<>();
        try
        {
            Collection<Part> parts = request.getParts();
            for (Part part : parts)
            {
                //取part名称
                String name = part.getName();
                //取part content-type
                String contenttype = part.getContentType();
                if (contenttype == null || contenttype.isEmpty())
                {
                    continue;
                }
                if (!name.toLowerCase().equals("file"))
                {
                    continue;
                }
                String filename = part.getSubmittedFileName();
                //获取文件名称
                if (filename == null || filename.isEmpty())
                {
                    continue;
                }
                FileCollection file = new FileCollection();
                file.InnerInit(part);
                fileList.add(file);
            }
        }
        catch (Exception ex)
        {
            System.out.println("获取http上传的文件异常!");
            ex.printStackTrace(System.out);
        }
        return fileList;
    }
}

包装文件服务操作接口,用来上传、下载、删除文件等

package JRT.Core.MultiPlatform;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.stream.Stream;

/**
 * 文件服务操作类,通过此类上传和下载文件等
 */
public class FileService {
    /**
     * 上传文件到文件服务
     *
     * @param serverPath   服务地址,如果是FTP就是FTP带密码的地址,,如果是网站就是检验service/JRTUpFileService.ashx地址
     * @param fileFullName 文件带路径的全名
     * @param fileNewName  文件上传到服务器的新名称
     * @param remotePath   相对路径
     * @return 空成功,非空返回失败原因
     */
    public String Upload(String serverPath, String fileFullName, String fileNewName, String remotePath) throws Exception {
        try {
            String ret = "";
            //普通ftp模式
            if (serverPath.toLowerCase().contains("ftp://")) {
                throw new Exception("此版本不支持FTP上传");
            }
            //检验http模式
            else if (serverPath.toLowerCase().contains("http://") || serverPath.toLowerCase().contains("https://")) {
                String remote = GetFileServiceRemoteAddr(serverPath);
                remotePath = remote + remotePath;
                //文件得到Base64串
                String fileBase64 = File2Base64Str(fileFullName);
                File fi = new File(fileFullName);
                String fileName = fi.getName();
                //新名称
                if (fileNewName != "") {
                    fileName = fileNewName;
                }
                //组装Post
                String paraStr = "Method=Upload&fileBase64Str=" + UrlEnCode(fileBase64) + "&fileName=" + UrlEnCode(fileName) + "&remotePath=" + UrlEnCode(remotePath);
                String retStr = GetHttpStr(serverPath, paraStr);
                return retStr;
            }
            //sftp模式
            else {
                return "-1^不支持的文件服务模式!";
            }
        } catch (Exception ex) {
            return ex.getMessage();
        }
    }


    /**
     * 上传文件到文件服务
     *
     * @param serverPath  服务地址,如果是FTP就是FTP带密码的地址,,如果是网站就是检验service/JRTUpFileService.ashx地址
     * @param stream      文件流
     * @param fileNewName 文件上传到服务器的新名称
     * @param remotePath  相对路径
     * @return 空成功,非空返回失败原因
     */
    public String Upload(String serverPath, InputStream stream, String fileNewName, String remotePath) {
        try {
            String ret = "";
            //普通ftp模式
            if (serverPath.toLowerCase().contains("ftp://")) {
                throw new Exception("此版本不支持FTP上传");
            }
            //检验http模式
            else if (serverPath.toLowerCase().contains("http://") || serverPath.toLowerCase().contains("https://")) {
                //得到相对路径
                String remote = GetFileServiceRemoteAddr(serverPath);
                remotePath = remote + remotePath;
                //流得到Base64
                String fileBase64 = Stream2Base64Str(stream);
                String fileName = fileNewName;
                //组装Post
                String paraStr = "Method=Upload&fileBase64Str=" + UrlEnCode(fileBase64) + "&fileName=" + UrlEnCode(fileName) + "&remotePath=" + UrlEnCode(remotePath);
                String retStr = GetHttpStr(serverPath, paraStr);
                return retStr;
            }
            //sftp模式
            else {
                return "-1^不支持的文件服务模式!";
            }
        } catch (Exception ex) {
            return ex.getMessage();
        }
    }

    /**
     * 从服务下载文件
     *
     * @param fileServerFullPath 文件在服务的全路径
     * @param fileFullName       文件本地保存的全路径
     * @param passive
     * @return 成功返回空串,否则返回失败原因
     */
    public String Download(String fileServerFullPath, String fileFullName, boolean passive) {
        try {
            //普通ftp模式
            if (fileServerFullPath.toLowerCase().contains("ftp://")) {
                throw new Exception("此版本还不支持FTP");
            }
            //检验http模式
            else if (fileServerFullPath.toLowerCase().contains("http://") || fileServerFullPath.toLowerCase().contains("https://")) {
                //忽略证书
                if (fileServerFullPath.contains("https://")) {
                    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
                    };
                    // Install the all-trusting trust manager
                    SSLContext sc = SSLContext.getInstance("SSL");
                    sc.init(null, trustAllCerts, new java.security.SecureRandom());
                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    // Create all-trusting host name verifier
                    HostnameVerifier allHostsValid = new HostnameVerifier() {
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    };
                }
                InputStream responseStream = null;
                FileOutputStream fileOutputStream = null;
                try {
                    URL u = new URL(UrlEnCode(fileServerFullPath));
                    HttpURLConnection http = (HttpURLConnection) u.openConnection();
                    http.setDoOutput(Boolean.TRUE);
                    http.setRequestMethod("GET");
                    int responseCode = http.getResponseCode();
                    responseStream = http.getInputStream();
                    Path fileFullNameP = Paths.get(fileFullName);
                    Path directoryName = fileFullNameP.getParent();
                    //本地路径不存在就创建
                    if (!Files.exists(directoryName)) {
                        Files.createDirectories(directoryName);
                    }
                    //文件存在就删除
                    if (Files.exists(fileFullNameP)) {
                        Files.delete(fileFullNameP);
                    }
                    fileOutputStream = new FileOutputStream(fileFullName);
                    // 创建一个byte数组来缓存读取的数据
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    // 读取InputStream中的数据,并将其写入到文件中
                    while ((bytesRead = responseStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, bytesRead);
                    }

                    return "";
                } catch (Exception ee) {
                    return ee.getMessage();
                } finally {
                    if (responseStream != null) {
                        responseStream.close();
                    }
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                }
            }
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "";
    }

    /**
     * 从服务下载文件
     *
     * @param fileServerFullPath 文件在服务的全路径
     * @param passive
     * @return
     */
    public InputStream DownloadStream(String fileServerFullPath, boolean passive) throws Exception {
        try {
            //普通ftp模式
            if (fileServerFullPath.toLowerCase().contains("ftp://")) {
                throw new Exception("此版本还不支持FTP");
            }
            //检验http模式
            else if (fileServerFullPath.toLowerCase().contains("http://") || fileServerFullPath.toLowerCase().contains("https://")) {
                //忽略证书
                if (fileServerFullPath.contains("https://")) {
                    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
                    };
                    // Install the all-trusting trust manager
                    SSLContext sc = SSLContext.getInstance("SSL");
                    sc.init(null, trustAllCerts, new java.security.SecureRandom());
                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    // Create all-trusting host name verifier
                    HostnameVerifier allHostsValid = new HostnameVerifier() {
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    };
                }
                URL u = new URL(UrlEnCode(fileServerFullPath));
                HttpURLConnection http = (HttpURLConnection) u.openConnection();
                http.setDoOutput(Boolean.TRUE);
                http.setRequestMethod("GET");
                int responseCode = http.getResponseCode();
                InputStream responseStream = http.getInputStream();
                return responseStream;
            }
        } catch (Exception ex) {
            throw ex;
        }
        return null;
    }


    /**
     * 修改文件名
     *
     * @param serverPath      服务地址,如果是FTP就是FTP带密码的地址,,如果是网站就是检验service/JRTUpFileService.ashx地址
     * @param currentFilename 当前文件名
     * @param newFilename     修改的文件名
     * @param remotePath      相对路径
     * @return 成功返回空串,否则返回原因
     */
    public String ReName(String serverPath, String currentFilename, String newFilename, String remotePath) {
        try {
            //普通ftp模式
            if (serverPath.toLowerCase().contains("ftp://")) {
                throw new Exception("此版本还不支持FTP");
            }
            //检验http模式
            else if (serverPath.toLowerCase().contains("http://") || serverPath.toLowerCase().contains("https://")) {
                String paraStr = "Method=ReName&currentFilename=" + UrlEnCode(serverPath + remotePath + currentFilename) + "&newFilename=" + UrlEnCode(serverPath + remotePath + newFilename);
                String retStr = GetHttpStr(GetFileServiceAddr(serverPath), paraStr);
                return retStr;
            }
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "";
    }

    /**
     * 移动文件
     *
     * @param currentFullFilename 原文件全路径
     * @param newFullFilename     新的文件全路径
     * @return 成功返回空串,否则返回原因
     */
    public String Move(String currentFullFilename, String newFullFilename) {
        try {
            //普通ftp模式
            if (currentFullFilename.toLowerCase().contains("ftp://")) {
                throw new Exception("此版本还不支持FTP");
            }
            //检验http模式
            else if (currentFullFilename.toLowerCase().contains("http://") || currentFullFilename.toLowerCase().contains("https://")) {
                String paraStr = "Method=ReName&currentFilename=" + UrlEnCode(currentFullFilename) + "&newFilename=" + UrlEnCode(newFullFilename);
                String retStr = GetHttpStr(GetFileServiceAddr(currentFullFilename), paraStr);
                return retStr;
            }
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "";
    }


    /**
     * 删除服务器上的文件
     *
     * @param fileServerFullPath 文件在服务的全路径
     * @return 成功返回空串,否则返回原因
     */
    public String Delete(String fileServerFullPath) {
        try {
            //普通ftp模式
            if (fileServerFullPath.toLowerCase().contains("ftp://")) {
                throw new Exception("此版本还不支持FTP");
            }
            //检验http模式
            else if (fileServerFullPath.toLowerCase().contains("http://") || fileServerFullPath.toLowerCase().contains("https://")) {
                String paraStr = "Method=Delete&fileName=" + UrlEnCode(fileServerFullPath);
                String retStr = GetHttpStr(GetFileServiceAddr(fileServerFullPath), paraStr);
                return retStr;
            }
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "";
    }


    /**
     * 文件路径的文件得到Base64串
     *
     * @param path 全路径
     * @return
     * @throws Exception
     */
    public static String File2Base64Str(String path) throws Exception {
        File file = new File(path);
        if (!file.exists()) {
            return "";
        }
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[(int) file.length()];
            fis.read(buffer);
            fis.close();
            ;
            return Base64.getEncoder().encodeToString(buffer);
        } catch (IOException e) {
            throw new RuntimeException("读文件异常:", e);
        }
    }

    /**
     * url编码
     *
     * @param url
     * @return
     * @throws Exception
     */
    private static String UrlEnCode(String url) throws Exception {
        String[] arr = url.split("/");
        String head = "";
        String left = "";
        for (int i = 0; i < arr.length; i++) {
            if (i < 3) {
                if (head.isEmpty()) {
                    head = arr[i];
                } else {
                    head = head + "/" + arr[i];
                }
            } else {
                left = left + "/" + URLEncoder.encode(arr[i], "UTF-8");
            }
        }
        return head + left;

    }

    /**
     * 通过服务地址得到相对服务地址
     *
     * @param serverPath 服务地址
     * @return 相对服务地址
     */
    private String GetFileServiceRemoteAddr(String serverPath) {
        String[] arr = serverPath.split("/");
        StringBuilder ret = new StringBuilder();
        boolean start = false;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].toLowerCase().equals("fileservice")) {
                start = true;
                continue;
            }
            if (start == true) {
                ret.append(arr[i]).append("/");
            }
        }
        return ret.toString();
    }

    /**
     * 流转Base64
     *
     * @param stream 流
     * @return Base64串
     * @throws IOException
     */
    public static String Stream2Base64Str(InputStream stream) throws IOException {
        byte[] buffer = new byte[stream.available()];
        stream.read(buffer);
        String encoded = Base64.getEncoder().encodeToString(buffer);
        return encoded;
    }

    /**
     * 从http下载文本
     *
     * @param url  url
     * @param para 参数
     * @return 文本串
     * @throws Exception
     */
    private static String GetHttpStr(String url, String para) throws Exception {
        byte[] bytes = para.getBytes("UTF-8");
        //忽略证书
        if (url.contains("https://")) {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }
            };

            // Install the all-trusting trust manager
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // Create all-trusting host name verifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
        }

        URL u = new URL(url);
        HttpURLConnection http = (HttpURLConnection) u.openConnection();
        http.setAllowUserInteraction(true);
        http.setDoOutput(Boolean.TRUE);
        http.setDoInput(Boolean.TRUE);
        http.setUseCaches(false);
        http.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        http.setInstanceFollowRedirects(false);
        http.setRequestMethod("POST");
        http.connect();

        OutputStream outputStream = http.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();

        InputStream is = http.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line + System.lineSeparator());
        }
        return stringBuilder.toString();
    }

    /**
     * 通过服务地址得到webservice服务地址
     *
     * @param serverPath 服务地址
     * @return webservice服务地址
     */
    private String GetFileServiceAddr(String serverPath) {
        String[] arr = serverPath.split("/");
        StringBuilder webHead = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i].toLowerCase().equals("fileservice")) {
                break;
            }
            webHead.append(arr[i]).append("/");
        }
        return webHead.toString() + "service/JRTUpFileService.ashx";
    }

}

测试文件操作后台代码

/**
	 * 上传文件到文件服务
	 * @return
	 */
	public String UpImageFile() throws Exception
	{
		//得到文件
		List<FileCollection> fileList=JRT.Core.MultiPlatform.JRTWebFile.GetFiles(Request);
		if(fileList!=null&&fileList.size()>0)
		{
			JRT.Core.MultiPlatform.FileService fileService=new JRT.Core.MultiPlatform.FileService();
			fileService.Upload("http://localhost:8080/JRTWeb/service/JRTUpFileService.ashx",fileList.get(0).GetInputStream(),fileList.get(0).GetFileName(),"/zlz");
		}
		return Helper.Success();
	}

	/**
	 * 改名文件
	 * @return
	 */
	public String ReNameImageFile() throws Exception
	{
		JRT.Core.MultiPlatform.FileService fileService=new JRT.Core.MultiPlatform.FileService();
		fileService.ReName("http://localhost:8080/JRTWeb/FileService/","logo.png","logo1.png","zlz/");
		return Helper.Success();
	}

	/**
	 * 删除文件
	 * @return
	 */
	public String DeleteImageFile() throws Exception
	{
		JRT.Core.MultiPlatform.FileService fileService=new JRT.Core.MultiPlatform.FileService();
		fileService.Delete("http://localhost:8080/JRTWeb/FileService/zlz/logo.png");
		fileService.Delete("http://localhost:8080/JRTWeb/FileService/zlz/logo1.png");
		return Helper.Success();
	}

前台代码

//上传文件到文件服务
            $("#btnUpfileBTTestCode").click(function () {
                $("#file_upload").click();
            });
            //改名文件
            $("#btnRenamefileBTTestCode").click(function () {
                //往后台提交数据
                $.ajax({
                    type: "post",
                    dataType: "json",
                    cache: false, //
                    async: true, //为true时,异步,不等待后台返回值,为false时强制等待;-asir
                    url: me.actionUrl + '?Method=ReNameImageFile',
                    success: function (data, status) {
                        $.messager.progress('close');
                        if (!FilterBackData(data)) {
                            return;
                        }
                        alert("成功");
                    }
                });
            });
            //删除文件
            $("#btnDeletefileBTTestCode").click(function () {
                //往后台提交数据
                $.ajax({
                    type: "post",
                    dataType: "json",
                    cache: false, //
                    async: true, //为true时,异步,不等待后台返回值,为false时强制等待;-asir
                    url: me.actionUrl + '?Method=DeleteImageFile',
                    success: function (data, status) {
                        $.messager.progress('close');
                        if (!FilterBackData(data)) {
                            return;
                        }
                        alert("成功");
                    }
                });
            });



//上传方法(HTML5)
        function http(date, url, callback) {
            function createXHttpRequest() {
                if (window.ActiveXObject) {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                else if (window.XMLHttpRequest) {
                    xmlhttp = new XMLHttpRequest();
                }
                else {
                    return;
                }
            }
            function starRequest(date) {
                createXHttpRequest();
                xmlhttp.onreadystatechange = function (e) {
                    if (xmlhttp.readyState == 4) {
                        if (xmlhttp.status == 200) {
                            if (e.srcElement.response.indexOf("false") > -1) {
                                showError(e.srcElement.response);
                                return;
                            }
                            callback(xmlhttp.response);
                        }
                    }
                };
                xmlhttp.open("POST", url, false);
                xmlhttp.send(date);
            }
            starRequest(date);
        }


        //上传文件
        function UpFileDo(a, ftp) {
            var selectFiles = document.getElementById('file_upload').files;
            if (selectFiles != null && selectFiles.length > 0) {
                for (var i = 0; i < selectFiles.length; i++) {
                    var data = new FormData();
                    var file = selectFiles[i];
                    if (ftp == null) {
                        ftp = "";
                    }
                    data.append("file", file);
                    ajaxLoading();
                    setTimeout(function () {
                        ajaxLoadEnd();
                    }, 4000);
                    var url = me.actionUrl + "?Method=UpImageFile";
                    var callback = function (retData) {
                        retData = JSON.parse(retData);
                        if (retData.IsOk) {
                            alert("上传成功");
                        }
                        else {
                            showError(retData["Message"]);
                        }
                        ajaxLoadEnd();
                    };
                    http(data, url, callback);
                }
                $("#file_upload").val("");
            }
        }

这样之后每个运行的网站内部都自带文件服务,方便开发测试文件服务相关功能,正式部署也不用额外弄文件服务了,如果用sftp之类的还得额外搭建和学习,前端加载还得特殊处理

文章来源:https://blog.csdn.net/zhanglianzhu_91/article/details/134910562
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。