简体   繁体   中英

Uploading an image from Android using the FILES request method to a php server

So I'm looking to upload an image from the user's phone to a php server using the FILES request method. I think this is the better choice as compared to POST. I've seen a handful of sample code for this, but it always uses POST and includes things like headers, strings, or MPEs. I just want to upload the image, nothing else. So here is my php:

$uploadedFile = $_FILES['image']['name'];

$uploadedType = $_FILES['image']['type'];

$uploadedSize = $_FILES['image']['size'];

$temp = $_FILES['image']['tmp_name'];

$error = $_FILES['image']['error'];

if ($error > 0) {
    die("File could not be uploaded. $error");
}
else {
    if ($uploadedType != ("image/jpg" || "image/png") || $uploadedSize > 500000) {
        die("Sorry, png and jpgs are the only supported filetypes.");
    }
    else {
        move_uploaded_file($temp, "images/".$uploadedFile);
        echo "Upload Complete. ".$uploadedType;
    }

}

This works with an html-based client. For android, I am able to retrieve the image's path, so right now I'm making a method which will take the path as a parameter, and then upload the image @ the given path to the web server.

Specific questions which cause confusion:

  1. Why is everyone using POST for this? I feel that FILES is the better choice from what I know of PHP. If I'm wrong please clarify.

  2. I have the path, so I'd do something like

    File file = new File(path);

then...

FileInputStream fis = new FileInputStream(file);

But then what from here? Sorry, a bit new at this.

So yea, I just need a push in the right direction I think, but most of the answers I've seen aren't really trying to accomplish what I am, or at least so I think. Thanks for your time.

The $_FILES variable is populated from a POST request. See the php documentation - It's even titeled "Post upload methods".

A simplified example to get you started:

public void upload(File file) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httpPost = new HttpPost();
    httpPost.setEntity(new FileEntity(file, "image/png"));
    client.execute(httpPost);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM