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 = "
";
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();
}
}
}
参考
其他上传图片文件的方式: