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

相关文章

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

SpringBoot全局异常拦截与自定义错误页面实现过程解读

《SpringBoot全局异常拦截与自定义错误页面实现过程解读》本文介绍了SpringBoot中全局异常拦截与自定义错误页面的实现方法,包括异常的分类、SpringBoot默认异常处理机制、全局异常拦... 目录一、引言二、Spring Boot异常处理基础2.1 异常的分类2.2 Spring Boot默

基于SpringBoot实现分布式锁的三种方法

《基于SpringBoot实现分布式锁的三种方法》这篇文章主要为大家详细介绍了基于SpringBoot实现分布式锁的三种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、基于Redis原生命令实现分布式锁1. 基础版Redis分布式锁2. 可重入锁实现二、使用Redisso

SpringBoo WebFlux+MongoDB实现非阻塞API过程

《SpringBooWebFlux+MongoDB实现非阻塞API过程》本文介绍了如何使用SpringBootWebFlux和MongoDB实现非阻塞API,通过响应式编程提高系统的吞吐量和响应性能... 目录一、引言二、响应式编程基础2.1 响应式编程概念2.2 响应式编程的优势2.3 响应式编程相关技术

C#实现将XML数据自动化地写入Excel文件

《C#实现将XML数据自动化地写入Excel文件》在现代企业级应用中,数据处理与报表生成是核心环节,本文将深入探讨如何利用C#和一款优秀的库,将XML数据自动化地写入Excel文件,有需要的小伙伴可以... 目录理解XML数据结构与Excel的对应关系引入高效工具:使用Spire.XLS for .NETC

Nginx更新SSL证书的实现步骤

《Nginx更新SSL证书的实现步骤》本文主要介绍了Nginx更新SSL证书的实现步骤,包括下载新证书、备份旧证书、配置新证书、验证配置及遇到问题时的解决方法,感兴趣的了解一下... 目录1 下载最新的SSL证书文件2 备份旧的SSL证书文件3 配置新证书4 验证配置5 遇到的http://www.cppc

Nginx之https证书配置实现

《Nginx之https证书配置实现》本文主要介绍了Nginx之https证书配置的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起... 目录背景介绍为什么不能部署在 IIS 或 NAT 设备上?具体实现证书获取nginx配置扩展结果验证

SpringBoot整合 Quartz实现定时推送实战指南

《SpringBoot整合Quartz实现定时推送实战指南》文章介绍了SpringBoot中使用Quartz动态定时任务和任务持久化实现多条不确定结束时间并提前N分钟推送的方案,本文结合实例代码给大... 目录前言一、Quartz 是什么?1、核心定位:解决什么问题?2、Quartz 核心组件二、使用步骤1

使用Redis实现会话管理的示例代码

《使用Redis实现会话管理的示例代码》文章介绍了如何使用Redis实现会话管理,包括会话的创建、读取、更新和删除操作,通过设置会话超时时间并重置,可以确保会话在用户持续活动期间不会过期,此外,展示了... 目录1. 会话管理的基本概念2. 使用Redis实现会话管理2.1 引入依赖2.2 会话管理基本操作

mybatis-plus分表实现案例(附示例代码)

《mybatis-plus分表实现案例(附示例代码)》MyBatis-Plus是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生,:本文主要介绍my... 目录文档说明数据库水平分表思路1. 为什么要水平分表2. 核心设计要点3.基于数据库水平分表注意事项示例