簡體   English   中英

使用PHP將文件從android(java)上傳到服務器

[英]Uploading file from android (java) to server using PHP

您好我試圖使用PHP將文件從我的Android應用程序上傳到我的服務器。

我看過這篇文章:

如何使用與PHP一起使用的Java HttpClient庫上傳文件 http://www.veereshr.com/Java/Upload 如何使用http將Android中的文件從移動設備發送到服務器?

這是我的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']

我在服務器日志中遇到了同樣的錯誤。

我想我的問題是我無法參考我上傳的文件。

謝謝你的幫助。

嘗試多部分實體

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
      }

嘗試這個:

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

您可能需要更改路徑以滿足您的需求,但上述代碼可以正常工作。

使用Android / C#{Xamarin}在Web服務器上上傳圖像

這只是一小段代碼。 它可以使用Android將任何圖像從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");     
   }
?>

暫無
暫無

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

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