簡體   English   中英

使用php和android將小型圖像上傳到服務器

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

在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

如何正確上傳圖片

這是我要上傳的代碼,可以正常工作。 您需要導入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);
$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM