[我想使用截击发送图像以及数据帮助我,我需要最简单的发送方法,请帮助我,我在邮递员中尝试过,我选择了文件而不是文本,并且一切顺利,我需要那样。
Map<String, String> params = new HashMap<String, String>();
params.put("number", strUserName.trim());
params.put("image", image);
JSONObject json = new JSONObject(params);
String url = "";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url
, json, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject object = new JSONObject(String.valueOf(response));
String status = object.getString("Status");
if (status.equals("200")) {
Intent intent = new Intent(MainActivity.this, OtpVerification.class);
intent.putExtra("mobile1",strUserName);
startActivity(intent);
finish();
} else if(status.equals("404")) {
Toast.makeText(MainActivity.this, "Please Enter Valid No.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("Ashish", " " + e);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(jsonObjectRequest);
}
示例代码:
Volley图片上传布局
用于创建以上布局,您可以使用以下xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Upload Image using Volley"
android:id="@+id/textView"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"/>
<Button
android:id="@+id/button_choose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:text="Browse Image"
android:textColor="#fff"
android:layout_gravity="center_horizontal"
android:layout_margin="20dp"
android:padding="10dp"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@drawable/border"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:layout_margin="20dp"/>
<Button
android:id="@+id/button_upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:text="upload"
android:textColor="#fff"
android:layout_gravity="center_horizontal"
android:layout_margin="20dp"/>
</LinearLayout>
现在进入MainActivity.java
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button btnChoose, btnUpload;
public static String BASE_URL = "http://192.168.1.100/AndroidUploadImage/upload.php";
static final int PICK_IMAGE_REQUEST = 1;
String filePath;
现在将OnClickListener
接口实现为我们的按钮。
btnChoose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
现在,我们将创建一种从图库中选择图像的方法。创建以下方法。
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
为了完成图像选择过程,我们需要重写以下方法。
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == PICK_IMAGE_REQUEST){
Uri picUri = data.getData();
filePath = getPath(picUri);
imageView.setImageURI(picUri);
}
}
}
// Get Path of selected image
private String getPath(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
有关Android图像的更多信息,请阅读Android ImageView的惊人事实。
现在运行您的应用程序,如果您可以从图库中选择图像,则可以继续。在下面的快照中,您可以看到我的应用正在运行。使用Volley上传图片
现在,我们需要再创建一个将图像上传到我们服务器的方法。在MainActivity
类中创建以下方法。
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr.addFile("image", imagePath);
MyApplication.getInstance().addToRequestQueue(smr);
}
因此,MainActivity.java
文件的最终完整代码将是
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button btnChoose, btnUpload;
public static String BASE_URL = "http://192.168.1.100/AndroidUploadImage/upload.php";
static final int PICK_IMAGE_REQUEST = 1;
String filePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
btnChoose = (Button) findViewById(R.id.button_choose);
btnUpload = (Button) findViewById(R.id.button_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
imageBrowse();
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (filePath != null) {
imageUpload(filePath);
} else {
Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
}
}
});
}
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if(requestCode == PICK_IMAGE_REQUEST){
Uri picUri = data.getData();
Log.d("picUri", picUri.toString());
Log.d("filePath", filePath);
imageView.setImageURI(picUri);
}
}
}
private void imageUpload(final String imagePath) {
SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jObj = new JSONObject(response);
String message = jObj.getString("message");
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
smr.addFile("image", imagePath);
MyApplication.getInstance().addToRequestQueue(smr);
}
// Get Path of selected image
private String getPath(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
}
现在最后向您的应用添加以下权限。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
MyApplication.java
public class MyApplication extends Application {
public static final String TAG = MyApplication.class.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
希望这会起作用!