// 代码网上抄的 忘记链接了 抱歉哈
packageupload;importjava.io.BufferedReader;importjava.io.DataOutputStream;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.net.URL;public classuploadtest {publicuploadtest() {//TODO Auto-generated constructor stub
}public static voidmain(String[] args)
{try{
upLoadByCommonPost("http://127.0.0.1/upload_file.php");
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}private static void upLoadByCommonPost(String uploadUrl) throwsIOException {
String end= "\r\n";
String twoHyphens= "--";
String boundary= "******";
URL url= newURL(uploadUrl);
HttpURLConnection httpURLConnection=(HttpURLConnection) url
.openConnection();
httpURLConnection.setChunkedStreamingMode(128 * 1024);//128K 应该按照文件大小来定义//允许输入输出流
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);//使用POST方法
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary=" +boundary);
DataOutputStream dos= newDataOutputStream(
httpURLConnection.getOutputStream());
dos.writeBytes(twoHyphens+ boundary +end);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"1.jpg\";" +end);
dos.writeBytes("Content-Type: image/jpeg" +end);
dos.writeBytes(end);
FileInputStream fis= new FileInputStream("d:\\1.jpg");byte[] buffer = new byte[1024*100]; //100k
int count = 0;//读取文件
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer,0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens+ boundary + twoHyphens +end);
dos.flush();
InputStream is=httpURLConnection.getInputStream();
InputStreamReader isr= new InputStreamReader(is, "utf-8");
BufferedReader br= newBufferedReader(isr);
String result;while ((result=br.readLine()) != null){
System.out.println(result);
}
dos.close();
is.close();
}
}