服务器图片-保存
一、路径、名称
/** * 获取文件名称,绝对路径 * @return */ public static String getFileName(){ String fileUrl="";//最终图片在服务器的绝对路径 String PATH="";//图片在服务器的绝对路径-文件夹 String month="";//图片月目录 String day="";//天目录 String fileName="";//文件名称 SimpleDateFormat sd = new SimpleDateFormat("yyyyMM");//月目录格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//天目录格式 month=sd.format(new Date()); day=sdf.format(new Date()); String uuid = UUID.randomUUID().toString().replaceAll("-", ""); fileName = uuid + ".jpg"; //目录创建 File file; file=new File(PATH); if(!file.exists() && !file .isDirectory()){ file .mkdir(); } file =new File(PATH +"/"+month); if(!file.exists() && !file .isDirectory()){ file .mkdir(); } file =new File(PATH +"/"+month+"/"+day); if(!file.exists() && !file .isDirectory()){ file .mkdir(); } fileUrl=fileUrl+"/"+month+"/"+month+"/"+day+"/"+fileName; return fileUrl; }
二、获取输入流
从微信服务器:
/** * 从微信服务器后去图片的输入流对象 * @param mediaId * @return * @throws IOException */ public static InputStream getMedia(String mediaId) throws IOException { //获取微信服务器,图片 String accessToken= "网页获取或者我也不知,百度吧";//根据实际获取此处 String url = "https://api.weixin.qq.com/cgi-bin/media/get"; String params = "access_token=" + accessToken + "&media_id=" + mediaId; String urlNameString = url + "?" + params; InputStream is = null; URL urlGet = new URL(urlNameString); HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(); http.setRequestMethod("GET"); // 必须是get方式请求 http.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); http.setDoOutput(true); http.setDoInput(true); http.connect(); // 获取文件转化为byte流 is = http.getInputStream(); return is; }
从前端:
三、保存文件
/** * 保存图片到本地服务器 * @return * @throws IOException */ public static String savaI() throws IOException { String pathUrl="图片的保存路径";//绝对路径,可以使用步骤一中获取文件名称的方法获取;根据实际需求获取文件路径,保存前,文件所在的文件夹需要创建出来。 InputStream inputStream ;//获取输入流 FileOutputStream os = new FileOutputStream(pathUrl);//获取指向文件的输出流 inputStream=getMedia("前端传入的media");//这里是从微信服务器获取的图片流对象
//从前端获取输入流对象,还没有整理,自己百度吧! int len = 0; byte[] data = new byte[1024]; while ((len = inputStream.read(data)) != -1) { os.write(data, 0, len); } return pathUrl; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律