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

时间:2014-01-04 07:40:52

标签: java php android eclipse

在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方面我正在使用

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

然而

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

返回null

如何正确上传图片

2 个答案:

答案 0 :(得分:1)

这是我的上传代码,它的工作原理。您需要导入httpmime jar

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代码

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

答案 1 :(得分:0)

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

替换为

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

检查手册以了解发布方法上传的可用字段。 http://www.php.net/manual/en/features.file-upload.post-method.php