doucou19961205 2013-08-30 10:05
浏览 60
已采纳

MultipartEntity实体代码不调用php代码/不工作

I am trying to push an image and some EditText into a server database. The codes does not show any error but it does not seem to be working.

I have included the following codes in my Manifest:

<uses-permission android:name="android.permission.INTERNET"/
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Android Codes:

public class ImageUpload extends Activity {
private static final int PICK_IMAGE = 1;
private ImageView imgView;
private Button upload;
private EditText TraineeID, ExamID, Invoiceno;
private Bitmap bitmap;
private ProgressDialog dialog;
private String url = "www.orgaar.com/androidlogin/imageupload.php";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.uploadimage);

    imgView = (ImageView) findViewById(R.id.ImageView);
    upload = (Button) findViewById(R.id.Upload);
    Invoiceno = (EditText) findViewById(R.id.Invoiceno);
    TraineeID = (EditText) findViewById(R.id.TraineeID);
    ExamID = (EditText) findViewById(R.id.ExamID); 
    upload.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if (bitmap == null) {
                Toast.makeText(getApplicationContext(),
                        "Please select image", Toast.LENGTH_SHORT).show();
            } else {
                dialog = ProgressDialog.show(ImageUpload.this, "Uploading",
                        "Please wait...", true);
                new ImageUploadTask().execute();
            }
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.imageupload_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.ic_menu_gallery:
        try {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Select Picture"),
                    PICK_IMAGE);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(),
                    e.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case PICK_IMAGE:
        if (resultCode == Activity.RESULT_OK) {
            Uri selectedImageUri = data.getData();
            String filePath = null;

            try {
                // OI FILE Manager
                String filemanagerstring = selectedImageUri.getPath();

                // MEDIA GALLERY
                String selectedImagePath = getPath(selectedImageUri);

                if (selectedImagePath != null) {
                    filePath = selectedImagePath;
                } else if (filemanagerstring != null) {
                    filePath = filemanagerstring;
                } else {
                    Toast.makeText(getApplicationContext(), "Unknown path",
                            Toast.LENGTH_LONG).show();
                    Log.e("Bitmap", "Unknown path");
                }

                if (filePath != null) {
                    decodeFile(filePath);
                } else {
                    bitmap = null;
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "Internal error",
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }
        }
        break;
    default:
    }
}


class ImageUploadTask extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... unsued) {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            entity.addPart("returnformat", new StringBody("json"));
            entity.addPart("uploaded", new ByteArrayBody(data,"myImage.jpg"));
            entity.addPart("Invoiceno", new StringBody(Invoiceno.getText().toString()));
            entity.addPart("TraineeID", new StringBody(TraineeID.getText().toString()));
            entity.addPart("ExamID", new StringBody(ExamID.getText().toString()));
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost,localContext);
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

            String sResponse = reader.readLine();
            return sResponse;
            } catch (Exception e) {
            Log.e(e.getClass().getName(), e.getMessage(), e);
            return null;
        }

        // (null);
    }

    @Override
    protected void onProgressUpdate(Void... unsued) {

    }

    @Override
    protected void onPostExecute(String sResponse) {
        try {
            if (dialog.isShowing())
                dialog.dismiss();

            if (sResponse != null) {
                JSONObject JResponse = new JSONObject(sResponse);
                int success = JResponse.getInt("SUCCESS");
                String message = JResponse.getString("MESSAGE");
                if (success == 0) {
                    Toast.makeText(getApplicationContext(), message,
                            Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Photo uploaded successfully",
                            Toast.LENGTH_SHORT).show();
                    Invoiceno.setText("");
                }
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(),
                    e.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if (cursor != null) {
        // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
        // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } else
        return null;
}

public void decodeFile(String filePath) {
    // Decode image size

    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);

    imgView.setImageBitmap(bitmap);

}
}

My PHP Codes:

<?php

if (!empty($_POST)) {

  require("config.inc.php");

  $fileDirectory = dirname(__FILE__); // this gives us the path to file folder

  $imagesDirectory = $fileDirectory . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR; 

  $newFileName = uniqid();

  require("fileupload.php");

 $query = "INSERT INTO image (Invoiceno, TraineeID, ExamID, image) VALUES (:Invoiceno,:TraineeID, :ExamID, :image)";

 $query_params = array(

   ':Invoiceno' => $_POST['Invoiceno'],
   ':TraineeID' => $_POST['TraineeID'],
   ':ExamID' => $_POST['ExamID'],
   ':image' => $newFileName,
);

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);

}

catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error. Couldn't add post!";
    die(json_encode($response));
}

$response["success"] = 1;
$response["message"] = "Username Successfully Added!";
echo json_encode($response);

} else {
?>
    <form action="imageupload.php" method= "post" enctype="multipart/form-data">
        <p>
        Inoviceno: <input type="text" name="Invoiceno">
        </p>
        <p>
        TraineeID:<input type="text" name="TraineeID">
        </P>
        <p>
        ExamID:<input type = "text" name = "ExamID">
        <p>
        Image: <input type="file" name="file">
        </p>
        <input type="submit" name="submit" value="Add photo"> 
   </form>
<?php
}
?>

fileupload.php:

<?php


// list of possible upload error codes
// copied from http://www.php.net/manual/en/features.file-upload.errors.php
$uploadErrors = array( 
    UPLOAD_ERR_OK        => "No errors.", 
    UPLOAD_ERR_INI_SIZE    => "Larger than upload_max_filesize.", 
    UPLOAD_ERR_FORM_SIZE    => "Larger than form MAX_FILE_SIZE.", 
    UPLOAD_ERR_PARTIAL    => "Partial upload.", 
    UPLOAD_ERR_NO_FILE        => "No file.", 
    UPLOAD_ERR_NO_TMP_DIR    => "No temporary directory.", 
    UPLOAD_ERR_CANT_WRITE    => "Can't write to disk.", 
    UPLOAD_ERR_EXTENSION     => "File upload stopped by extension.", 

); 

// list of possible file types accepted
// here we only allow jpg and png and gif
$fileTypes = array(
    'image/pjpeg',
    'image/jpeg',
    'image/png',
    'image/gif'
);

// default value for unsuccessful move file
$successfullyMoveFile = false;

// the name of the input type 
$fileInputName = 'file';

// an array to store all the possible errors related to uploading a file
$fileErrorMessages = array();

$uploadFile = !empty($_FILES);

if ($uploadFile) {
    $fileUploaded = $_FILES[$fileInputName];

    // if we have errors while uploading!!
    if ($fileUploaded['error'] != UPLOAD_ERR_OK) {
        $errorCode = $fileUploaded['error']; // this could be 1, 2, 3, 4, 5, 6, or 7.
        $fileErrorMessages['file'] = $uploadErrors[$errorCode];
    }

    // now we check for file type
    $fileTypeUploaded = $fileUploaded['type'];

    $fileTypeNotAllowed = !in_array($fileTypeUploaded, $fileTypes);
    if ($fileTypeNotAllowed) {
        $fileErrorMessages['file'] = 'You should upload a .jpg, .png or .gif file';
    }

    // if successful, we want to copy the file to our images folder
    if ($fileUploaded['error'] == UPLOAD_ERR_OK) {

        $successfullyMoveFile = move_uploaded_file($fileUploaded["tmp_name"], $imagesDirectory . $newFileName);

    }
}
?>

Please tell me what I am missing or whats wrong with my codes thanks. Is it that my PHP codes are wrong?

Latest Error :

08-30 18:35:37.685: E/java.lang.IllegalStateException(9159): Target host must not be null, or set in parameters. scheme=null, host=null, path=www.orgaar.com/androidlogin/imageupload.php
  • 写回答

1条回答 默认 最新

  • duanheyi7147 2013-08-30 10:14
    关注

    do like this

    class ImageUploadTask extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... unsued) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(url);
    
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
                entity.addPart("returnformat", new StringBody("json"));
                entity.addPart("uploaded", new FileBody(new File(filePath), getMimeType(filePath)));
                //entity.addPart("uploaded", new ByteArrayBody(data,"myImage.jpg"));
                entity.addPart("Invoiceno", new StringBody(Invoiceno.getText().toString()));
                entity.addPart("TraineeID", new StringBody(TraineeID.getText().toString()));
                entity.addPart("ExamID", new StringBody(ExamID.getText().toString()));
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost,localContext);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    
                String sResponse = reader.readLine();
                return sResponse;
                } catch (Exception e) {
                Log.e(e.getClass().getName(), e.getMessage(), e);
                return null;
            }
    
            // (null);
        }
    
    public static String getMimeType(String filePath) {
            String type = null;
            String extension = getFileExtensionFromUrl(filePath);
            if (extension != null) {
                MimeTypeMap mime = MimeTypeMap.getSingleton();
                type = mime.getMimeTypeFromExtension(extension);
            }
            return type;
        }
    

    UPDATE

    public static String getFileExtensionFromUrl(String url) {
            int dotPos = url.lastIndexOf('.');
            if (0 <= dotPos) {
                return (url.substring(dotPos + 1)).toLowerCase();
            }
    
            return "";
        }
    

    UPDATE 2 Declare filePath variable here and remove from OnActivityRes

    private String filePath;
    private static final int PICK_IMAGE = 1;
    private ImageView imgView;
    private Button upload;
    private EditText TraineeID, ExamID, Invoiceno;
    private Bitmap bitmap;
    private ProgressDialog dialog;
    private String url = "www.orgaar.com/androidlogin/imageupload.php";
    

    UPDATE 3 try

    entity.addPart("file", new FileBody(new File(filePath), getMimeType(filePath)));

    instead of

    entity.addPart("uploaded", new FileBody(new File(filePath), getMimeType(filePath)));

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制