上傳檔案之至用戶端處理http請求

來源:互聯網
上載者:User

標籤:上傳圖片 檔案


Android用戶端主要代碼:

 

public ImageHttp(Context context) {super(context);filePath = context.getCacheDir().getAbsolutePath();}public void uploadUserImg(Bitmap bitmap,IHttpSenderCallBack<String> callback) {this.callback = callback;File file = getFile(bitmap);// 注意與服務端協商if (file == null) {return;}List<Parameter> parameters = new ArrayList<Parameter>();parameters.add(new Parameter("file", file));uploadFile("uploadImg", parameters);}private File getFile(Bitmap bitmap) {File file = null;String path = filePath + "/image.jpg";if (bitmap != null && !StringUtil.emptyOrNull(path)) {try {FileOutputStream out = new FileOutputStream(path);bitmap.compress(Bitmap.CompressFormat.JPEG, 60, out);out.flush();out.close();file = new File(path);} catch (FileNotFoundException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}return file;}


 

protected String uploadFile(String methodName, List<Parameter> parameter) {String errorMsg = "";try {String serviceUrl = getPostUrl(methodName);HttpPost httpPost = new HttpPost(serviceUrl);//採用http4包,不需要再添加  multipart/form-data表單 ,切記,這兒耽擱了好久MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); // 檔案傳輸if (parameter != null && !parameter.isEmpty()) {for (int i = 0; i < parameter.size(); i++) {Parameter p = parameter.get(i);if ("file".equals(p.getKey())) {mpEntity.addPart(p.getKey(),new FileBody(((File) p.getValue())));} else {mpEntity.addPart(p.getKey(), new StringBody(p.getValue().toString()));}}httpPost.setEntity(mpEntity);}HttpClient httpclient = new DefaultHttpClient();httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);HttpResponse httpResponse = httpclient.execute(httpPost);String result = "";int status = httpResponse.getStatusLine().getStatusCode();LogUtil.d("httpResponseCode--------->" + status);if (status == HttpStatus.SC_OK) {result = EntityUtils.toString(httpResponse.getEntity());}parseProperty_(result, methodName);result = "";} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}return errorMsg;}


 

上傳檔案之至用戶端處理http請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.