在MultipartUploadRequest中上传期间出错

时间:2018-11-11 11:59:30

标签: php android mysql android-studio image-uploading

我正在尝试使用MultipartUploadRequest将图像上传到服务器。我已经使用Postman进行了测试,并且一切正常。但是,当我尝试通过电话上传图像时,出现“上传过程中出错”错误。我已经使用println进行测试。 MultipartUploadRequest中的所有代码均已执行。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
private Bitmap bitmap;
private Uri filePath;
private int PICK_IMAGE_REQUEST = 1;
private static final int STORAGE_PERMISSION_CODE = 2342;
private static final String UPLOAD_URL = "http://172.20.10.6/UploadPhoto6/upload.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    requestStoragePermission();

    buttonChoose = findViewById(R.id.buttonChoose);
    buttonUpload = findViewById(R.id.buttonUpload);
    imageView = findViewById(R.id.imageView);
    editText = findViewById(R.id.editTextName);

    buttonChoose.setOnClickListener(this);
    buttonUpload.setOnClickListener(this);
}

private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null)
    {
        filePath = data.getData();
        try
        {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

//method to get the file path from uri
public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();

    return path;
}

private void uploadImage()
{
    String name = editText.getText().toString().trim();
    String path = getPath (filePath);

    try
    {
        String uploadId = UUID.randomUUID().toString();
        new MultipartUploadRequest (this, uploadId, UPLOAD_URL)
            .addFileToUpload (path,"image")
            .addParameter("name", name)
            .setNotificationConfig (new UploadNotificationConfig())
            .setMaxRetries(2)
            .startUpload();
        System.out.println ("All codes executed");
    }
    catch (Exception e)
    {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

private void requestStoragePermission()
{
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
        return;

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE))
    {
    }

    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
    if (requestCode == STORAGE_PERMISSION_CODE) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
        }
        else
        {
            Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
        }
    }
}

@Override
public void onClick(View v) {
    if (v == buttonChoose) {
        showFileChooser();
    }
    if (v == buttonUpload) {
        uploadImage();
    }
}
}

这是我的upload.php

<?php
require_once 'dbDetails.php';
$upload_path = 'uploads/';
$server_ip = gethostbyname (gethostname());
$upload_url = 'http://'.$server_ip.'/UploadPhoto6/'.$upload_path;
$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if (isset ($_POST['name']) and isset ($_FILES['image']['name']))
    {
    $con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die ('unable to connect to database');
    $name = $_POST['name'];

    $fileinfo = pathinfo($_FILES['image']['name']);
    $extension = $fileinfo['extension'];
    $file_url = $upload_url.getFileName().'.'.$extension;
    $file_path = $upload_path.getFileName().'.'.$extension;

    try
    {
        move_uploaded_file ($_FILES['image']['tmp_name'], $file_path);
        $sql = "INSERT INTO images (url,name) VALUES ('$file_url' , '$name')";

        if (mysqli_query($con,$sql))
        {
            $response['error']=false;
            $response['url'] = $file_url;
            $response ['name'] = $name;
        }
    }
    catch (Exception $e)
    {
        $response['error'] = true;
        $respin['message'] = $e->getMessage();
    }
    mysqli_close ($con);        
}
else
{
    $response ['error'] = true;
    $response ['message'] = 'please choose a file';
}   

echo json_encode ($response);
}

function getFileName()
{
$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ('Unable to connect');
$sql = "SELECT max(id) as id FROM images";
$result = mysqli_fetch_array(mysqli_query($con,$sql));
mysqli_close ($con);
if ($result['id']==null)
{
    return 1;
}
else
{
    return ++$result['id'];
}
}

0 个答案:

没有答案