經過form表單進行上傳文件 php
<html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>
public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread() { public void run() { try { doUPloadFile(); } catch (Exception e) { e.printStackTrace(); } }; }.start(); } public HttpClient createClient() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.DEFAULT_CONTENT_CHARSET); params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30 * 1000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 30 * 1000); SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg); return new DefaultHttpClient(conMgr, params); } void doUPloadFile() throws Exception { // 須要上傳的文件 File file = new File("/storage/sdcard0/test.png"); FileInputStream fis = new FileInputStream(file); HttpClient httpclient = createClient(); String url = ""; MultipartEntity me = new MultipartEntity();//須要下載第三方jar包(httpmime.jar) me.addPart("file", new InputStreamBody(fis, file.getName())); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(me); HttpResponse httpResponse = httpclient.execute(httpPost); int code = httpResponse.getStatusLine().getStatusCode(); log("http status code:" + code); if (code == HttpStatus.SC_OK) { String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8); // 上傳的結果,能夠使json,或者是返回上傳後文件的的url Log.v("result = " + result); Log.v("上傳成功"); } } }