溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android如何實(shí)現(xiàn)上傳圖片至java服務(wù)器

發(fā)布時(shí)間:2021-04-17 09:37:33 來源:億速云 閱讀:225 作者:小新 欄目:移動(dòng)開發(fā)

小編給大家分享一下Android如何實(shí)現(xiàn)上傳圖片至java服務(wù)器,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

這幾天有做到一個(gè)小的案例,手機(jī)拍照、相冊(cè)照片上傳到服務(wù)器??蛻舳撕头?wù)器的代碼都貼出來:

客戶端

AndroidManifest.xml添加以下權(quán)限

<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() {
  //這里就寫了從相冊(cè)中選擇圖片,相機(jī)拍照的就略過了
  Intent galleryIntent = new Intent(Intent.ACTION_PICK,
  android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
 }

 //當(dāng)圖片被選中的返回結(jié)果
 @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 };

    // 獲取游標(biāo)
    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();
    }
    // 當(dāng) Http 響應(yīng)碼'500'
    else if (statusCode == 500) {
     Toast.makeText(getApplicationContext(),
       "Something went wrong at server end", Toast.LENGTH_LONG).show();
    }
    // 當(dāng) Http 響應(yīng)碼 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();
  }
 }
}

服務(wù)端

這里用是Intellij Idea 2016.3.1+Tomcat 搭建的本地服務(wù)器,前篇文章有介紹具體的搭建步驟。
服務(wù)端項(xiàng)目結(jié)構(gòu):UploadImage.javauploadimg.jsp`、lib庫

Android如何實(shí)現(xiàn)上傳圖片至java服務(wù)器

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>

運(yùn)行結(jié)果:

客戶端

Android如何實(shí)現(xiàn)上傳圖片至java服務(wù)器

服務(wù)端

Android如何實(shí)現(xiàn)上傳圖片至java服務(wù)器

以上是“Android如何實(shí)現(xiàn)上傳圖片至java服務(wù)器”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI