0

我正在尝试将图像和一些 EditText 推送到服务器数据库中。代码没有显示任何错误,但似乎没有工作。

我在我的清单中包含了以下代码:

<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" />

安卓代码:

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);

}
}

我的 PHP 代码:

<?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
}
?>

文件上传.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);

    }
}
?>

请告诉我我缺少什么或我的代码有什么问题,谢谢。是我的PHP代码错误吗?

最新错误:

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
4

1 回答 1

0

这样做

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;
    }

更新

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

        return "";
    }

更新 2 在此处声明 filePath 变量并从 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";

更新 3 尝试

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

代替

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

于 2013-08-30T10:14:12.027 回答