java post 文件上传
package upload;
import com.loop.core.modules.kit.RandomKit;
import org.junit.Test;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by IntelliJ IDEA.
* Author: kid 86883772@qq.cm
* Description: 文件上传
* Date:2016/12/20.
* Time:9:38.
*/
public class FileUpload {
@Test
public void uploadTest() {
String res = uploadImage("http://wechat.kid.be-xx.com/kidtest/upload", new File("C:\\Users\\Haitao\\Desktop\\t\\t2.jpg"), (System.currentTimeMillis()) + ".jpg");
System.out.println("Res:" + res);
}
public String uploadImage(String url, File file, String fileName) {
String res = "";
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
String split = "--";
String boundary = getBoundary();
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
OutputStream outputStream = new DataOutputStream(conn.getOutputStream());
StringBuffer imageData = new StringBuffer();
imageData.append("\r\n").append(split).append(boundary).append("\r\n");
imageData.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"").append("\r\n");
imageData.append("Content-Type:image/png");
imageData.append("\r\n\r\n");
outputStream.write(imageData.toString().getBytes());
//读取文件信息
readFile(outputStream, file);
byte[] endData = ("\r\n" + split + boundary + split + "\r\n").getBytes();
outputStream.write(endData);
outputStream.flush();
outputStream.close();
res = InputStreamToString(conn.getInputStream());
} catch (Throwable t) {
t.printStackTrace();
} finally {
return res;
}
}
private void readFile(OutputStream outputStream, File file) throws IOException {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
int len = 0;
byte[] b = new byte[1024];
while ((len = fis.read(b)) != -1) {
outputStream.write(b, 0, len);
}
} catch (IOException io) {
throw io;
} finally {
if (null != fis) {
fis.close();
}
}
}
private String getBoundary() {
return RandomKit.ice.getRandomOfLetterAndNumber(32, true);
}
private String InputStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
boolean firstLine = true;
try {
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (!firstLine) {
stringBuilder.append(System.getProperty("line.separator"));
} else {
firstLine = false;
}
stringBuilder.append(line);
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
return stringBuilder.toString();
}
}
}