絮叨
昨天实现了 PHP 上传图片到 zimg 服务器,下面简单介绍一下如何使用 Java 上传图片到 zimg,并获取相应图片的返回信息
使用 Java 实现上传
根据 zimg 使用文档,我们需要让 zimg 返回 json 信息,不能使用表单形式上传图片,下面是 Java 演示代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
| 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;
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; }
private static String sendPost(String url, byte[] PostData, String fileType) { OutputStream outStream = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); URLConnection conn = realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", fileType); conn.setDoOutput(true); conn.setDoInput(true); outStream = conn.getOutputStream(); outStream.write(PostData); outStream.flush();
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 { try { if (outStream != null) { outStream.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
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 改成你需要上传的图片的路径