post 上传图片
写在前面的:
代码中标黄的地方“Content-Type: image/jpeg” ,服务器端得到文件才会是“xxx.jpeg”;
网上大多数代码都是“Content-Type: application/octet-stream” ,这时服务器端得到的文件是“xxx.octet-stream”
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class PostFileTest { public static void main(String[] args) { String filePath = "E:\\2.jpg"; String urlS = "http://localhost:8070/SpringMVCTest/hellofile/uploadfile"; try{ String boundary = "Boundary-b1ed-4060-99b9-fca7ff59c113"; //Could be any string String Enter = "\r\n"; File file = new File(filePath); FileInputStream fis = new FileInputStream(file); URL url = new URL(urlS); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary); conn.connect(); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); //part 1 String part1 = "--" + boundary + Enter + "Content-Type: image/jpeg" + Enter + "Content-Disposition: form-data; filename=\""+file.getName()+"\"; name=\"file\"" + Enter + Enter; //part 2 String part2 = Enter + "--" + boundary + Enter + "Content-Type: text/plain" + Enter + "Content-Disposition: form-data; name=\"dataFormat\"" + Enter + Enter + "hk" + Enter + "--" + boundary + "--"; System.out.println("part1: "+part1); System.out.println("part2: "+part2); byte[] fileBytes = new byte[fis.available()]; fis.read(fileBytes); dos.writeBytes(part1); dos.write(fileBytes); dos.writeBytes(part2); dos.flush(); dos.close(); fis.close(); System.out.println("status code: "+conn.getResponseCode()); // 得到响应流 InputStream responseStream = conn.getInputStream(); // 获取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(responseStream)); String line; StringBuilder message = new StringBuilder(); while ((line = reader.readLine()) != null) { message.append(line); } // 获取返回信息 //return message.toString(); System.out.println("return: "+message.toString()); conn.disconnect(); }catch(Exception e){ e.printStackTrace(); } } }
参考
java 发送文件(Http Post),带其他参数
Java POST请求发送文件同时发送参数
其他上次图片文件的方式:
HttpClient用法--这一篇全了解(内含例子)
如何用java网络编程实现本地文件上传到服务器?