我正在尝试将图像及其标题上传到Android中的MYSQL服务器。但是,当我使用画廊来获取图像时它工作正常,但现在我在应用程序中引入了相机它无法正常工作。
我知道有类似的问题,但我无法解决我的问题。
这是按钮的代码:
btnupload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
GetImageNameEditText = textIn.getText().toString();
ImageUploadToServerFunction();
}
});
这是我的图像选择方法:
private void SelectImage(){
final CharSequence[] items = {"Camera","Gallery","Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(Uploadcamera.this);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if(items[i].equals("Camera")){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,REQUEST_CAMERA);
}else if(items[i].equals("Gallery")){
Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent,"Select File"),SELECT_FILE);
}else if(items[i].equals("Cancel")){
dialogInterface.dismiss();
}
}
});
builder.show();
}
这是活动结果
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,requestCode,data);
if(resultCode== Activity.RESULT_OK){
if (requestCode==REQUEST_CAMERA){
Bundle bundle = data.getExtras();
final Bitmap bmp = (Bitmap)bundle.get("data");
imageView.setImageBitmap(bmp);
}
if (requestCode==SELECT_FILE){
Uri seletecdImageUri = data.getData();
imageView.setImageURI(seletecdImageUri);
}
}
}
这是我的图片上传功能和连接代码:
public void ImageUploadToServerFunction(){
ByteArrayOutputStream byteArrayOutputStreamObject ;
byteArrayOutputStreamObject = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStreamObject);
byte[] byteArrayVar = byteArrayOutputStreamObject.toByteArray();
final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);
class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Uploadcamera.this,"Image is Uploading","Please Wait",false,false);
}
@Override
protected void onPostExecute(String string1) {
super.onPostExecute(string1);
// Dismiss the progress dialog after done uploading.
progressDialog.dismiss();
// Printing uploading success message coming from server on android app.
Toast.makeText(Uploadcamera.this,string1,Toast.LENGTH_LONG).show();
// Setting image as transparent after done uploading.
imageView.setImageResource(android.R.color.transparent);
}
@Override
protected String doInBackground(Void... params) {
ImageProcessClass imageProcessClass = new ImageProcessClass();
HashMap<String,String> HashMapParams = new HashMap<String,String>();
HashMapParams.put(ImageName, GetImageNameEditText);
HashMapParams.put(ImagePath, ConvertImage);
String FinalData = imageProcessClass.ImageHttpRequest(ServerUploadPath, HashMapParams);
return FinalData;
}
}
AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
AsyncTaskUploadClassOBJ.execute();
}
public class ImageProcessClass{
public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) {
StringBuilder stringBuilder = new StringBuilder();
try {
URL url;
HttpURLConnection httpURLConnectionObject ;
OutputStream OutPutStream;
BufferedWriter bufferedWriterObject ;
BufferedReader bufferedReaderObject ;
int RC ;
url = new URL(requestURL);
httpURLConnectionObject = (HttpURLConnection) url.openConnection();
httpURLConnectionObject.setReadTimeout(19000);
httpURLConnectionObject.setConnectTimeout(19000);
httpURLConnectionObject.setRequestMethod("POST");
httpURLConnectionObject.setDoInput(true);
httpURLConnectionObject.setDoOutput(true);
OutPutStream = httpURLConnectionObject.getOutputStream();
bufferedWriterObject = new BufferedWriter(
new OutputStreamWriter(OutPutStream, "UTF-8"));
bufferedWriterObject.write(bufferedWriterDataFN(PData));
bufferedWriterObject.flush();
bufferedWriterObject.close();
OutPutStream.close();
RC = httpURLConnectionObject.getResponseCode();
if (RC == HttpsURLConnection.HTTP_OK) {
bufferedReaderObject = new BufferedReader(new InputStreamReader(httpURLConnectionObject.getInputStream()));
stringBuilder = new StringBuilder();
String RC2;
while ((RC2 = bufferedReaderObject.readLine()) != null){
stringBuilder.append(RC2);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private String bufferedWriterDataFN(HashMap<String, String> HashMapParams) throws UnsupportedEncodingException {
StringBuilder stringBuilderObject;
stringBuilderObject = new StringBuilder();
for (Map.Entry<String, String> KEY : HashMapParams.entrySet()) {
if (check)
check = false;
else
stringBuilderObject.append("&");
stringBuilderObject.append(URLEncoder.encode(KEY.getKey(), "UTF-8"));
stringBuilderObject.append("=");
stringBuilderObject.append(URLEncoder.encode(KEY.getValue(), "UTF-8"));
}
return stringBuilderObject.toString();
}
}
我做错了什么?
答案 0 :(得分:0)
你可以试试Volley
private void uploadImage_Server(String url) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
//Your API Response
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//Showing toast for API error or timeout error
Toast.makeText(Imageupload.this, volleyError.toString(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String, String> parameters = new Hashtable<String, String>();
//Adding parameters like that
parameters.put("key", value(image in base64);
//returning parameters
return parameters;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(Imageupload.this);
//Adding request to the queue
requestQueue.add(stringRequest);
}