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之类的还得额外搭建和学习,前端加载还得特殊处理

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/220389.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

往上走^^

欢迎来到程序小院 往上走 玩法&#xff1a;转动的圆球&#xff0c;点击固定到上方的圆中即可往上走一步&#xff0c;转动超过上面圆即游戏结束&#xff0c; 往上走一步加1分&#xff0c;快去往上走吧^^。开始游戏https://www.ormcc.com/play/gameStart/218 html <canvas wi…

Gin之GORM 查询语句

前期工作可以看之前的&#xff08;连接数据库&#xff1b;以及确定要操作的库&#xff09; Gin之GORM 操作数据库&#xff08;MySQL&#xff09;-CSDN博客https://blog.csdn.net/m0_72264240/article/details/134948202?spm1001.2014.3001.5502这次我们操作gin库下的另外一个…

Android--Jetpack--数据库Room详解二

本是青灯不归客&#xff0c;却因浊酒恋红尘 一&#xff0c;基本使用 关于Room数据库的基本使用&#xff0c;请参考文章Android--Jetpack--数据库Room详解一-CSDN博客 二&#xff0c;Room与ViewModle,LiveData的结合使用 LiveData与ViewModle的使用&#xff0c;请参考文章Andr…

文章解读与仿真程序复现思路——电力系统自动化EI\CSCD\北大核心《考虑移动式储能调度的配电网灾后多源协同孤岛运行策略》

这篇文章的标题表明研究的主题是在配电网发生灾害后&#xff0c;采用一种策略来实现多源协同孤岛运行&#xff0c;并在这个过程中特别考虑了移动式储能的调度。 让我们逐步解读标题的关键词&#xff1a; 考虑移动式储能调度&#xff1a; 文章关注的焦点之一是移动式储能系统的…

国标GB28181安防监控系统/磁盘阵列EasyCVR(V.3.4)新亮点:免保活功能

TSINGSEE青犀近日发布了EasyCVR安防管理平台的V.3.4版本&#xff0c;其中一大亮点就是很多朋友都在咨询的“免保活”功能&#xff0c;那么&#xff0c;什么是“免保活”功能&#xff1f;又该如何配置呢&#xff1f; 在EasyCVR平台有个【按需直播】按钮&#xff0c;顾名思义&…

ARM流水灯

.text .global _start _start: LED1 1.RCC时钟使能GPIOE RCC_MP_AHB4ENSETR[4]->1 LDR R0,0x50000a28 LDR R1,[R0] ORR R1,R1,#(0x1<<4) STR R1,[R0] 2.设置PE10为输出模式 GPIOE_MODER[21:20]->01 先清0 LDR R0,0x50006000 LDR R1,[R0] BIC R1,R1,#(0x3<&…

Linux | 多线程

前言 本文主要介绍多线程基础知识&#xff0c;以及使用多线程技术进行并发编程&#xff1b;最后会介绍生产者消费者模型&#xff1b; 一、线程基本认识 1、什么是线程 如果你是科班出生&#xff0c;你肯定听过线程相关概念&#xff1b;但是你可能没有真正搞懂什么是线程&#…

集群监控Zabbix和Prometheus

文章目录 一、Zabbix入门概述1、Zabbix概述2、Zabbix 基础架构3、Zabbix部署3.1 前提环境准备3.2 安装Zabbix3.3 配置Zabbix3.4 启动停止Zabbix 二、Zabbix的使用与集成1、Zabbix常用术语2、Zabbix实战2.1 创建Host2.2 创建监控项&#xff08;Items&#xff09;2.3 创建触发器&…

以太网协议与DNS

以太网协议 以太网协议DNS 以太网协议 以太网用于在计算机和其他网络设备之间传输数据,以太网既包含了数据链路层的内容,也包含了物理层的内容. 以太网数据报: 其中目的IP和源IP不是网络层的目的IP和源IP,而是mac地址.网络层的主要负责是整体的转发过程,数据链路层负责的是局…

Data Mining数据挖掘—2. Classification分类

3. Classification Given a collection of records (training set) – each record contains a set of attributes – one of the attributes is the class (label) that should be predicted Find a model for class attribute as a function of the values of other attribu…

Vue3中使用tinymce, tinymce上传图片,tinymce使用emoji表情

1.效果图 2. 安装 npm i tinymce npm i tinymce/tinymce-vue在node_modules文件夹中找到tinymce下的skins复制到项目public文件夹中子组件 <template><editor v-model"myValue" :init"init" :disabled"disabled" :id"tinymceId&…

小型洗衣机哪个牌子质量好?五款高性价比内衣洗衣机推荐

随着内衣洗衣机的流行&#xff0c;很多小伙伴在纠结该不该入手一款内衣洗衣机&#xff0c;专门来洗一些贴身衣物&#xff0c;答案是非常有必要的&#xff0c;因为我们现在市面上的大型洗衣机只能做清洁&#xff0c;无法对我们的贴身衣物进行一个高强度的清洁&#xff0c;而小小…

浅谈 USB Bulk 深入浅出 (3) - USB Bulk 装置传输的注意事项

来源&#xff1a;大大通 作者&#xff1a;冷氣團 1 USB Bulk 是什么 USB 是即插即用使用差动信号的装置界面&#xff0c;是以 端点 ( Endpoint )&#xff0c;做为传输装置的输出入端&#xff0c;透过不同的端点 ( Endpoint ) 和模式&#xff0c;来进行与装置的沟通&#xff…

antv - G6 绘制1:N N:1 跨节点的graph

文章目录 hover时候&#xff0c;当前节点高亮&#xff0c;且直接相连的线和节点也高亮展示&#xff08;展示直接关系&#xff09;节点的label超过10个字的时候&#xff0c;文本溢出&#xff0c;且hover有tooltip&#xff1b;小于10个字&#xff0c;没有tooltiptootip使用插件mo…

getchar的功能和用法

getchar()是C语言中的一个标准库函数&#xff0c;用于从标准输入&#xff08;通常是键盘&#xff09;读取一个字符&#xff0c;并将其作为int类型返回。它通常用于从键盘获取用户输入。 getchar()函数在程序中等待用户输入&#xff0c;当用户输入一个字符并按下回车键后&#…

Vue路由跳转重定向动态路由VueCli

Vue路由跳转&重定向&动态路由&VueCli 一、声明式导航-导航链接 1.需求 实现导航高亮效果 如果使用a标签进行跳转的话&#xff0c;需要给当前跳转的导航加样式&#xff0c;同时要移除上一个a标签的样式&#xff0c;太麻烦&#xff01;&#xff01;&#xff01; …

做题总结 160.链表相交

160.链表相交 我的思路代码改进 LeetCode&#xff1a;给你两个单链表的头节点 headA 和 headB &#xff0c;请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点&#xff0c;返回 null 。 我的思路 计算链表A、B的长度count1、count2。临时指针curA、curB要同时指向…

SpringMVC学习笔记

先赞后看&#xff0c;养成习惯&#xff01;&#xff01;&#xff01;❤️ ❤️ ❤️ 资源收集不易&#xff0c;如果喜欢可以关注我哦&#xff01; ​如果本篇内容对你有所启发&#xff0c;欢迎访问我的个人博客了解更多内容&#xff1a;链接地址 是什么 Spring MVC是Spring框架…

C++面向对象(OOP)编程-友元(友元函数和友元类)

本文主要介绍面向对象编程的友元的使用&#xff0c;以及友元的特性和分类&#xff0c;提供C代码。 1 为什么引进友元 面向对象编程&#xff08;OOP&#xff09;的三大特性中的封装&#xff0c;是通过类实现对数据的隐藏和封装。一般定义类的成员变量为私有成员&#xff0c;成员…

模拟目录管理 - 华为OD统一考试(C卷)

OD统一考试(C卷) 分值: 200分 题解: Java / Python / C++ 题目描述 实现一个模拟目录管理功能的软件,输入一个命令序列,输出最后一条命令运行结果。 支持命令: 1)创建目录命令: mkdir 目录名称,如mkdir abc为在当前目录创建abc目录,如果已存在同名目录则不执行任何操作…