我想创建一个应用程序,将大型图像(使用智能手机捕获,因此大小超过3MB)上传到PHP服务器和带有图像路径的数据库。我已经使用volley库https://www.simplifiedcoding.net/upload-image-to-server/来学习本教程
但我想要两个不同的按钮。一个用于选择图像,另一个用于上传图像。我知道我做错了什么。因为它给了我null
位图。我不知道自己要改变什么。
编辑:MainActivity.java
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
//ImageView to display image selected
ImageView imageView;
String filePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing views
imageView = (ImageView) findViewById(R.id.imageView);
//checking the permission
//if the permission is not given we will open setting to add permission
//else app will not open
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
finish();
startActivity(intent);
return;
}
//adding click listener to button
findViewById(R.id.buttonChooseImage).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//if everything is ok we will open image chooser
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//calling the method uploadBitmap to upload image
uploadBitmap(filePath);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
//getting the image Uri
Uri imageUri = data.getData();
filePath = getPath(imageUri);
//displaying selected image to imageview
imageView.setImageURI(imageUri);
}
}
// 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;
}
private void uploadBitmap(final String imagePath) {
//our custom volley request
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, EndPoints.UPLOAD_URL,
new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse response) {
try {
JSONObject obj = new JSONObject(new String(response.data));
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/*
* Here we are passing image by renaming it with a unique name
* */
@Override
protected Map<String, String> getParams() {
//Converting Bitmap to String
String image = getFileDataFromDrawable(bitmap);
Map<String, String> params = new HashMap<>();
params.put("pic", imagePath);
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
}
答案 0 :(得分:0)
可能是因为在php中你可以发送的最大大小是2Mg,试着发送一张不到2M的图片,如果它的工作你必须去php.ini并更改max_size
答案 1 :(得分:0)
我使用此代码上传文件,并且我没有遇到上传14MB以上文件的问题。
HttpURLConnection conn = null;
DataOutputStream dos = null;
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024;
final File sourceFile = file_to_upload;
String serverResponseMessage;
String response = null;
if (!sourceFile.isFile()) {
return "no file";
} else {
try {
FileInputStream fileInputStream =
new FileInputStream(sourceFile.getPath());
URL url = "upload_URL";
conn = (HttpURLConnection) url.openConnection();
int size = (int) sourceFile.length();
conn.setFixedLengthStreamingMode(size);
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = 0;
long total_bytes = 0;
Log.e("start", "" + size);
do {
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
dos.write(buffer, 0, bufferSize);
total_bytes += bytesRead;
float f1 = total_bytes;
float f2 = size;
float f3 = f1 / f2;
publishProgress(f3);
} while (bytesRead > 0);
int serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
response = "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode;
fileInputStream.close();
dos.flush();
dos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException ex) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}