服务器图片-保存

一、路径、名称

    /**
     * 获取文件名称,绝对路径
     * @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; }

 

posted @ 2021-11-02 09:43  hehehenhen  阅读(151)  评论(0)    收藏  举报