国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

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

2019-12-12 00:35:03
字體:
供稿:網(wǎng)友

這幾天有做到一個小的案例,手機拍照、相冊照片上傳到服務器。客戶端和服務器的代碼都貼出來:

客戶端

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圖片轉(zhuǎn)碼為String    encodedString = Base64.encodeToString(byte_arr, 0);    return "";   }   @Override   protected void onPostExecute(String msg) {    prgDialog.setMessage("Calling Upload");    // 將轉(zhuǎn)換后的圖片添加到上傳的參數(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>

運行結果:

客戶端

服務端

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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 泰兴市| 叙永县| 旬阳县| 武隆县| 慈利县| 类乌齐县| 甘洛县| 麻江县| 益阳市| 英吉沙县| 馆陶县| 天祝| 都江堰市| 汕尾市| 阜南县| 台南市| 上犹县| 克拉玛依市| 祁阳县| 盱眙县| 瑞丽市| 香河县| 沽源县| 涟水县| 夏邑县| 浦北县| 洛扎县| 砀山县| 辽中县| 靖宇县| 汤原县| 共和县| 济南市| 东丽区| 阜南县| 奉新县| 运城市| 固原市| 谷城县| 郴州市| 凉城县|