How to send local .png to .php file on server using java application?

I have a local .png file that I want to send using POST data to a .php script that will save the data to a .png file on the server. How do I do this? Do I have to encode or something? All I have is a File and a way to POST data. Here is how I am sending the .png: public static byte[] imageToByte(File file) throws FileNotFoundException { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; try { for (int readNum; (readNum = != -1;) { bos.write(buf, 0, readNum); } } catch (IOException ex) { } byte[] bytes = bos.toByteArray(); return bytes; } public static void sendPostData(String url, HashMap data) throws Exception { URL siteUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); Set keys = data.keySet(); Iterator keyIter = keys.iterator(); String content = ""; for (int i = 0; keyIter.hasNext(); i++) { Object key =; if (i != 0) { content += "&"; } content += key + "=" + URLEncoder.encode(data.get(key), "UTF-8"); } System.out.println(content); out.writeBytes(content); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line = ""; while ((line = in.readLine()) != null) { System.out.println(line); } in.close(); } The PHP script:
When I try to upload, the image is corrupt. When I open the .png with notepad, I see that everything is the same as the local file except there are '\0's instead of 'NUL's

以上就是How to send local .png to .php file on server using java application?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准