使用PHP将Android(Java)中的文件上传到服务器

5

你好,我正在尝试使用PHP从我的Android应用程序将文件上传到我的服务器。

我已阅读以下文章:

如何使用Java HttpClient库上传文件,并与PHP一起工作 http://www.veereshr.com/Java/Upload 如何在Android上使用http从移动设备向服务器发送文件?

这是我的JAVA代码:

public void upload() throws Exception {

        File file = new File("data/data/com.tigo/databases/exercise");

        Log.i("file.getName()", file.getName());

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://***.***.***.***/backDatabase.php");

        InputStreamEntity reqEntity = new InputStreamEntity( new FileInputStream(file), -1);
        reqEntity.setContentType("binary/octet-stream");    

        reqEntity.setChunked(true);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);

        if((response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
            // Successfully Uploaded
            Log.i("uploaded", response.getStatusLine().toString());
        }
        else{
            // Did not upload. Add your logic here. Maybe you want to retry.
            Log.i(" not uploaded", response.getStatusLine().toString());
        }

        httpclient.getConnectionManager().shutdown();
    }

这是我的 PHP 代码:
<?php


    $uploads_dir = '/tigo/databaseBackup';

    if (is_uploaded_file($_FILES['exercise']['tmp_name']))
    {

    $info =  "File ". $_FILES['exercise']['name'] ." uploaded successfully.\n";
    $file = 'emailTest.log';
    file_put_contents($file, $info, FILE_APPEND | LOCK_EX);

    move_uploaded_file ($_FILES['exercise'] ['tmp_name'], $_FILES['exercise'] ['name']);

    } 
    else 
    {

    $info =  "Possible file upload attack: ";
    $file = 'emailTest.log';
    file_put_contents($file, $info, FILE_APPEND | LOCK_EX);

    $info =  "filename '". $_FILES['exercise']['tmp_name'] . "'.";
    file_put_contents($file, $info, FILE_APPEND | LOCK_EX);

    print_r($_FILES);

    }

?>

在我的logcat中,我得到了HTTP/1.1 200 OK的响应。 但是当我查看服务器日志时,发现出现了以下错误:

PHP Notice:  Undefined index: exercise in /var/www/backDatabase.php on line 23

我也尝试使用以下方法:

$_FILES['userfile']['name']

相比于

$_FILES['exercise']['tmp_name']

我在服务器日志中也遇到了同样的错误。

我认为我的问题是无法获取上传文件的引用。

感谢您的帮助。

3个回答

4
尝试使用多部分实体。
public void upload(String filepath) throws IOException
    {
     HttpClient httpclient = new DefaultHttpClient();
     httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
     HttpPost httppost = new HttpPost("url");
     File file = new File(filepath);
     MultipartEntity mpEntity = new MultipartEntity();
     ContentBody cbFile = new FileBody(file, "image/jpeg");
     mpEntity.addPart("userfile", cbFile); 
     httppost.setEntity(mpEntity);
     System.out.println("executing request " + httppost.getRequestLine());
     HttpResponse response = httpclient.execute(httppost);
     HttpEntity resEntity = response.getEntity();
             // check the response and do what is required
      }

你不需要创建 FileInputStream 吗? - Francisco Corrales Morales

0

试试这个:

JAVA 代码:

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;

public class UploadFile {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

HttpPost httppost = new HttpPost("http://***.***.***.***/backDatabase.php");
File file = new File("/data/data/com.tigo/databases/exercise");

MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("userfile", cbFile);

httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}

httpclient.getConnectionManager().shutdown();
}
}

PHP 代码:

<?php  
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) { 
  echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
  move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']); 
}  else  { 
   echo "Possible file upload attack: "; 
  echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
 print_r($_FILES); }
 ?>

您可能需要更改路径以适应您的需求,但上述代码是有效的。


嗨,我遇到了这个错误。构造函数FileBody(File,String)未定义。 - dasdasd
添加到 build_path: http://www.java2s.com/Code/JarDownload/httpmime/httpmime-4.2.5.jar.zip - Pedro Lobito

-1

使用Android / C# {Xamarin}上传图像到Web服务器

这只是一小段代码。它可以使用Android将任何图像发送到您的Web服务器。

System.Net.WebClient Client = new System.Net.WebClient();
Client.Headers.Add("Content-Type", "binary/octet-stream");
byte[] result = Client.UploadFile("localhost/FolderName/upload.php", "POST", path);
string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);

这是 PHP 代码 {upload.php}。在您的应用程序中创建一个名为{Uploads}的文件夹。
<?php

   $uploads_dir = 'uploads/'; //Directory to save the file that comes from client application.      
   if ($_FILES["file"]["error"] == UPLOAD_ERR_OK)       
   {      
     $tmp_name = $_FILES["file"]["tmp_name"];     
     $name = $_FILES["file"]["name"];    
     move_uploaded_file($tmp_name, "$uploads_dir/$name");     
   }
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接