简体   繁体   English

使用php和android将小型图像上传到服务器

[英]Uploading a small sized image to server using php and android

On PHP Side I am using following Code 在PHP方面,我正在使用以下代码

    $val = (isset($_GET['file']) ? $_GET['file'] : null);
        $isUploaded = false;
        return $val;
        if($val != null)
        {
            if (move_uploaded_file(@$_FILES['file']['tmp_name'], $mainPath))
            {
                $isUploaded = true;
            }
        }

Android side I am using 我正在使用的Android端

 List<NameValuePair> params = new ArrayList<NameValuePair>();
 params.add(new BasicNameValuePair("file", Base64Coder.encodeLines(imageArray)));

HttpResponse response = null;
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter("http.connection-manager.timeout", 15000);
        try {

            HttpPost httppost = new HttpPost(url);
             httppost.setEntity(entity);
                response = httpclient.execute(httppost);

However 然而

   $val = (isset($_GET['file']) ? $_GET['file'] : null);

returns null 返回null

How can I upload image properly 如何正确上传图片

This is my code for upload, and it's work. 这是我要上传的代码,可以正常工作。 You need import httpmime jar 您需要导入httpmime jar

PHP code PHP代码

$uploads_dir = '/Library/WebServer/Documents/Upload/upload/'.$_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
    echo $_POST["contentString"]."\n";
    echo  "File path = ".$uploads_dir;
    move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $uploads_dir);
} else {
    echo "\n Upload Error";
    echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
    print_r($_FILES);

JAVA code JAVA代码

HttpClient client = new DefaultHttpClient();
HttpPost postMethod = new HttpPost("http://localhost/Upload/index.php");

File file = new File(filePath);

MultipartEntity entity = new MultipartEntity();
FileBody contentFile = new FileBody(file);
entity.addPart("userfile",contentFile);

StringBody contentString = new StringBody("This is contentString");
entity.addPart("contentString",contentString);

postMethod.setEntity(entity);
HttpResponse response = client.execute(postMethod);
HttpEntity httpEntity = response.getEntity();
String state = EntityUtils.toString(httpEntity);
$val = (isset($_GET['file']) ? $_GET['file'] : null);

Replace with 用。。。来代替

$val = (isset($_FILES['file']['name']) ? $_FILES['file']['name'] : null);

Check manual for available fields for post method uploads. 在手册中查看有关后期方法上传的可用字段。 http://www.php.net/manual/en/features.file-upload.post-method.php http://www.php.net/manual/en/features.file-upload.post-method.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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