1. 絮叨

昨天实现了 PHP 上传图片到 zimg 服务器,下面简单介绍一下如何使用 Java 上传图片到 zimg,并获取相应图片的返回信息

2. 使用 Java 实现上传

根据 zimg 使用文档,我们需要让 zimg 返回 json 信息,不能使用表单形式上传图片,下面是 Java 演示代码


package cn.gitos.aurthur.zimg;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

// Created by Aurthur on 2016/10/19.

public class TestZimg {
    public static void main(String[] args) {
        String upload_url = "http://192.168.0.99:5000/upload";
        String image_file = "/tmp/test.jpg";
        String ext = getExtensionName(image_file);
        System.out.println(sendPost(upload_url, imageBinary(image_file, ext), ext));

    }

    private static byte[] imageBinary(String file_path, String fileType) {
        File f = new File(file_path);
        BufferedImage bi;
        try {
            bi = ImageIO.read(f);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(bi, fileType, bos);
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    // 向指定 URL 发送POST方法的请求
    private static String sendPost(String url, byte[] PostData, String fileType) {
        OutputStream outStream = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", fileType);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //二进制
            outStream = conn.getOutputStream();
            outStream.write(PostData);
            outStream.flush();

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    //Java文件操作 获取文件扩展名
    private static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
}

如果想测试代码的话,请把上面的 upload_url 改成你自己的 zimg 服务器地址,并把 image_file 改成你需要上传的图片的路径