JRT文件服务实现

2023-12-11 09:28
文章标签 实现 服务 jrt

本文主要是介绍JRT文件服务实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

在这里插入图片描述

在这里插入图片描述

首先实现文件服务的服务端,就是一个业务脚本,用来接收上传、移动和删除文件请求,老的是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-typeString 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;}//组装PostString 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;//流得到Base64String fileBase64 = Stream2Base64Str(stream);String fileName = fileNewName;//组装PostString 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 managerSSLContext sc = SSLContext.getInstance("SSL");sc.init(null, trustAllCerts, new java.security.SecureRandom());HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());// Create all-trusting host name verifierHostnameVerifier 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 managerSSLContext sc = SSLContext.getInstance("SSL");sc.init(null, trustAllCerts, new java.security.SecureRandom());HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());// Create all-trusting host name verifierHostnameVerifier 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 managerSSLContext sc = SSLContext.getInstance("SSL");sc.init(null, trustAllCerts, new java.security.SecureRandom());HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());// Create all-trusting host name verifierHostnameVerifier 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时强制等待;-asirurl: 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时强制等待;-asirurl: 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之类的还得额外搭建和学习,前端加载还得特殊处理

这篇关于JRT文件服务实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/480207

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

【区块链 + 人才服务】可信教育区块链治理系统 | FISCO BCOS应用案例

伴随着区块链技术的不断完善,其在教育信息化中的应用也在持续发展。利用区块链数据共识、不可篡改的特性, 将与教育相关的数据要素在区块链上进行存证确权,在确保数据可信的前提下,促进教育的公平、透明、开放,为教育教学质量提升赋能,实现教育数据的安全共享、高等教育体系的智慧治理。 可信教育区块链治理系统的顶层治理架构由教育部、高校、企业、学生等多方角色共同参与建设、维护,支撑教育资源共享、教学质量评估、

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P

【区块链 + 人才服务】区块链集成开发平台 | FISCO BCOS应用案例

随着区块链技术的快速发展,越来越多的企业开始将其应用于实际业务中。然而,区块链技术的专业性使得其集成开发成为一项挑战。针对此,广东中创智慧科技有限公司基于国产开源联盟链 FISCO BCOS 推出了区块链集成开发平台。该平台基于区块链技术,提供一套全面的区块链开发工具和开发环境,支持开发者快速开发和部署区块链应用。此外,该平台还可以提供一套全面的区块链开发教程和文档,帮助开发者快速上手区块链开发。

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、