最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android實現(xiàn)上傳圖片至java服務器

 更新時間:2018年08月16日 16:40:42   作者:Ericpengjun  
這篇文章主要為大家詳細介紹了Android實現(xiàn)上傳圖片至java服務器的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下

這幾天有做到一個小的案例,手機拍照、相冊照片上傳到服務器??蛻舳撕头掌鞯拇a都貼出來:

客戶端

AndroidManifest.xml添加以下權限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

客戶端的上傳圖片activity_upload.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/activity_main"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <ImageView
  android:id="@+id/imageView"
  android:layout_width="match_parent"
  android:layout_height="300dp"/>

 <EditText
  android:id="@+id/editText"
  android:layout_width="match_parent"
  android:layout_height="42dp"
  android:layout_margin="16dp"
  android:background="@drawable/edit_text_bg"/>

 <Button
  android:id="@+id/choose_image"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="選擇圖片"/>

 <Button
  android:id="@+id/upload_image"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="上傳圖片"/>

</LinearLayout>

UploadActivity.java界面代碼

package com.eric.uploadimage;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.ByteArrayOutputStream;
import cz.msebera.android.httpclient.Header;

@SuppressLint("NewApi")
public class UploadActivity extends AppCompatActivity implements View.OnClickListener {

 private EditText editTextName;
 private ProgressDialog prgDialog;

 private int RESULT_LOAD_IMG = 1;
 private RequestParams params = new RequestParams();
 private String encodedString;
 private Bitmap bitmap;
 private String imgPath;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  prgDialog= new ProgressDialog(this);
  prgDialog.setCancelable(false);

  editTextName = (EditText) findViewById(R.id.editText);
  findViewById(R.id.choose_image).setOnClickListener(this);
  findViewById(R.id.upload_image).setOnClickListener(this);
 }

 @Override
 public void onClick(View view) {
  switch (view.getId()) {
   case R.id.choose_image:
    loadImage();
    break;
   case R.id.upload_image:
    uploadImage();
    break;
  }
 }

 public void loadImage() {
  //這里就寫了從相冊中選擇圖片,相機拍照的就略過了
  Intent galleryIntent = new Intent(Intent.ACTION_PICK,
  android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
 }

 //當圖片被選中的返回結果
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  try {
   if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {

    Uri selectedImage = data.getData();
    String[] filePathColumn = { MediaStore.Images.Media.DATA };

    // 獲取游標
    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
    cursor.moveToFirst();

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    imgPath = cursor.getString(columnIndex);
    cursor.close();
    ImageView imgView = (ImageView) findViewById(R.id.imageView);
    imgView.setImageBitmap(BitmapFactory.decodeFile(imgPath)); 
   } else {
    Toast.makeText(this, "You haven't picked Image",
      Toast.LENGTH_LONG).show();
   }
  } catch (Exception e) {
   Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
  }
 }

 //開始上傳圖片
 private void uploadImage() {
  if (imgPath != null && !imgPath.isEmpty()) {
   prgDialog.setMessage("Converting Image to Binary Data");
   prgDialog.show();
   encodeImagetoString();
  } else {
   Toast.makeText(getApplicationContext(), "You must select image from gallery before you try to upload",
     Toast.LENGTH_LONG).show();
  }
 }


 public void encodeImagetoString() {
  new AsyncTask<Void, Void, String>() {

   protected void onPreExecute() {

   };

   @Override
   protected String doInBackground(Void... params) {
    BitmapFactory.Options options = null;
    options = new BitmapFactory.Options();
    options.inSampleSize = 3;
    bitmap = BitmapFactory.decodeFile(imgPath,
      options);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    // 壓縮圖片
    bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
    byte[] byte_arr = stream.toByteArray();
    // Base64圖片轉碼為String
    encodedString = Base64.encodeToString(byte_arr, 0);
    return "";
   }

   @Override
   protected void onPostExecute(String msg) {
    prgDialog.setMessage("Calling Upload");
    // 將轉換后的圖片添加到上傳的參數(shù)中
    params.put("image", encodedString);
    params.put("filename", editTextName.getText().toString());
    // 上傳圖片
    imageUpload();
   }
  }.execute(null, null, null);
 }

 public void imageUpload() {
  prgDialog.setMessage("Invoking JSP");
  String url = "http://172.18.2.73:8080/upload/uploadimg.jsp";
  AsyncHttpClient client = new AsyncHttpClient();
  client.post(url, params, new AsyncHttpResponseHandler() {
   @Override
   public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
    prgDialog.hide();
    Toast.makeText(getApplicationContext(), "upload success", Toast.LENGTH_LONG).show();
   }

   @Override
   public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {
    prgDialog.hide();
    if (statusCode == 404) {
     Toast.makeText(getApplicationContext(),
       "Requested resource not found", Toast.LENGTH_LONG).show();
    }
    // 當 Http 響應碼'500'
    else if (statusCode == 500) {
     Toast.makeText(getApplicationContext(),
       "Something went wrong at server end", Toast.LENGTH_LONG).show();
    }
    // 當 Http 響應碼 404, 500
    else {
     Toast.makeText(
       getApplicationContext(), "Error Occured n Most Common Error: n1. Device " +
         "not connected to Internetn2. Web App is not deployed in App servern3." +
         " App server is not runningn HTTP Status code : "
         + statusCode, Toast.LENGTH_LONG).show();
    }
   }
  });
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
  if (prgDialog != null) {
   prgDialog .dismiss();
  }
 }
}

服務端

這里用是Intellij Idea 2016.3.1+Tomcat 搭建的本地服務器,前篇文章有介紹具體的搭建步驟。
服務端項目結構:UploadImage.javauploadimg.jsp`、lib庫

UploadImage.java 類

public class UploadImage {

 public static void convertStringtoImage(String encodedImageStr, String fileName) {

  try {
   // Base64解碼圖片
   byte[] imageByteArray = Base64.decodeBase64(encodedImageStr);

   //
   FileOutputStream imageOutFile = new FileOutputStream("D:/uploads/" + fileName+".jpg");
   imageOutFile.write(imageByteArray);

   imageOutFile.close();

   System.out.println("Image Successfully Stored");
  } catch (FileNotFoundException fnfe) {
   System.out.println("Image Path not found" + fnfe);
  } catch (IOException ioe) {
   System.out.println("Exception while converting the Image " + ioe);
  }
 }
}

uploadimg.jsp 文件

<%@page import="com.eric.UploadImage"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>圖片上傳</title>
</head>
<body>
<%
 String imgEncodedStr = request.getParameter("image");
 String fileName = request.getParameter("filename");
 System.out.println("Filename: "+ fileName);
 if(imgEncodedStr != null){
  UploadImage.convertStringtoImage(imgEncodedStr, fileName);
  out.print("Image upload complete, Please check your directory");
 } else{
  out.print("Image is empty");
 }
%>
</body>
</html>

運行結果:

客戶端

服務端

覺得還不錯的小伙伴們點個贊,鼓勵一下!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • 淺談Android ASM自動埋點方案實踐

    淺談Android ASM自動埋點方案實踐

    本篇文章主要介紹了淺談Android ASM自動埋點方案實踐,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • Kotlin實現(xiàn)圖片選擇器的關鍵技術點總結

    Kotlin實現(xiàn)圖片選擇器的關鍵技術點總結

    這篇文章主要給大家介紹了關于Kotlin實現(xiàn)圖片選擇器的一些關鍵技術點,這是一個我在學習Kotlin過程中的一個練手項目,非常適合學習Kotlin的時候參考,需要的朋友可以參考下
    2021-09-09
  • Kotlin Service服務組件開發(fā)詳解

    Kotlin Service服務組件開發(fā)詳解

    這幾天分析了一下的啟動過程,于是乎,今天寫一下Service使用; 給我的感覺是它并不復雜,千萬不要被一坨一坨的代碼嚇住了,雖然彎彎繞繞不少,重載函數(shù)一個接著一個,就向走迷宮一樣,但只要抓住主線閱讀,很快就能找到出口
    2022-12-12
  • Android App調試內存泄露之Cursor篇

    Android App調試內存泄露之Cursor篇

    最近在工作中處理了一些內存泄露的問題,在這個過程中我尤其發(fā)現(xiàn)了一些基本的問題反而忽略導致內存泄露
    2012-11-11
  • Android仿Flipboard動畫效果的實現(xiàn)代碼

    Android仿Flipboard動畫效果的實現(xiàn)代碼

    這篇文章主要介紹了Android仿Flipboard動畫效果的實現(xiàn)代碼,本文圖文并茂給大家介紹的非常詳細,需要的朋友可以參考下
    2018-01-01
  • Android模擬開關按鈕點擊打開動畫(屬性動畫之平移動畫)

    Android模擬開關按鈕點擊打開動畫(屬性動畫之平移動畫)

    這篇文章主要介紹了Android模擬開關按鈕點擊打開動畫(屬性動畫之平移動畫)的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-09-09
  • listview里子項有按鈕的情況使用介紹

    listview里子項有按鈕的情況使用介紹

    不知大家有沒有遇到過listview里子項有按鈕的情況哈,本文自定義了按鈕并且在布局中做了引用,適合初學者哦,感興趣的也可以了解下
    2013-03-03
  • Android中單例模式的一些坑小結

    Android中單例模式的一些坑小結

    這篇文章主要給大家介紹了關于Android中單例模式的一些坑,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-02-02
  • Android如何調用系統(tǒng)相機拍照

    Android如何調用系統(tǒng)相機拍照

    這篇文章主要為大家詳細介紹了Android如何調用系統(tǒng)相機拍照的相關代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-09-09
  • Android自定義DataTimePicker實例代碼(日期選擇器)

    Android自定義DataTimePicker實例代碼(日期選擇器)

    本篇文章主要介紹了Android自定義DataTimePicker實例代碼(日期選擇器),非常具有實用價值,需要的朋友可以參考下。
    2017-01-01

最新評論

清水县| 海口市| 崇仁县| 宣化县| 枣庄市| 曲阳县| 怀来县| 军事| 兴和县| 汝州市| 会同县| 嘉鱼县| 嘉禾县| 兴宁市| 同德县| 佛教| 陇西县| 沙雅县| 潞西市| 泸西县| 施甸县| 宜春市| 徐汇区| 汉中市| 纳雍县| 益阳市| 侯马市| 榕江县| 都昌县| 安达市| 拉孜县| 江门市| 博野县| 黄冈市| 秦安县| 马鞍山市| 朔州市| 博白县| 娱乐| 政和县| 比如县|