当前位置: 首页 > 知识库问答 >
问题:

从Android设备在php服务器中上传文件

厉文栋
2023-03-14

我正试图从我的android设备上传文件到php服务器,但服务器没有收到任何文件。这是我的示例代码,我在网上找到的。php服务器,我正在通过chunk上传文件

我的Android代码

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;

private String upLoadServerUri = null;
private String imagepath=null;
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    uploadButton = (Button)findViewById(R.id.uploadButton);
    messageText  = (TextView)findViewById(R.id.messageText);
    btnselectpic = (Button)findViewById(R.id.button_selectpic);
    imageview = (ImageView)findViewById(R.id.imageView_pic);

    btnselectpic.setOnClickListener(this);
    uploadButton.setOnClickListener(this);
    upLoadServerUri = "http://192.168.2.4/fileupload/UploadToServer.php";
}


@Override
public void onClick(View arg0) {
    if(arg0==btnselectpic)
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
    }
    else if (arg0==uploadButton) {

         dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
         messageText.setText("uploading started.....");
         new Thread(new Runnable() {
             public void run() {

                  uploadFile(imagepath);

             }
           }).start();     
    }

} 

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1 && resultCode == RESULT_OK) {
        //Bitmap photo = (Bitmap) data.getData().getPath(); 

        Uri selectedImageUri = data.getData();
        imagepath = getPath(selectedImageUri);
        Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
        imageview.setImageBitmap(bitmap);
        messageText.setText("Uploading file path:" +imagepath);

    }
}
     public String getPath(Uri uri) {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }

public int uploadFile(String sourceFileUri) {


      String fileName = sourceFileUri;

      HttpURLConnection conn = null;
      DataOutputStream dos = null;  
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024; 
      File sourceFile = new File(sourceFileUri); 

      if (!sourceFile.isFile()) {

           dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"+imagepath);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"+ imagepath);
               }
           }); 

           return 0;

      }
      else
      {
           try { 

                 // open a URL connection to the Servlet
               FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);

               // Open a HTTP  connection to  the URL
               conn = (HttpURLConnection) url.openConnection(); 
               conn.setDoInput(true); // Allow Inputs
               conn.setDoOutput(true); // Allow Outputs
               conn.setUseCaches(false); // Don't use a Cached Copy
               conn.setRequestMethod("POST");
               conn.setRequestProperty("Connection", "Keep-Alive");
               conn.setRequestProperty("ENCTYPE", "multipart/form-data");
               conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
               conn.setRequestProperty("file", fileName); 

               dos = new DataOutputStream(conn.getOutputStream());

               dos.writeBytes(twoHyphens + boundary + lineEnd); 
               dos.writeBytes("Content-Disposition: form-data; name=\"file\";file\""
                                         + fileName + "\"" + lineEnd);

               dos.writeBytes(lineEnd);

               // create a buffer of  maximum size
               bytesAvailable = fileInputStream.available(); 

               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               buffer = new byte[bufferSize];

               // read file and write it into form...
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

               while (bytesRead > 0) {

                 dos.write(buffer, 0, bufferSize);
                 bytesAvailable = fileInputStream.available();
                 bufferSize = Math.min(bytesAvailable, maxBufferSize);
                 bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                }

               // send multipart form data necesssary after file data...
               dos.writeBytes(lineEnd);
               dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

               // Responses from the server (code and message)
               serverResponseCode = conn.getResponseCode();
               String serverResponseMessage = conn.getResponseMessage();

               Log.i("uploadFile", "HTTP Response is : "
                       + serverResponseMessage + ": " + serverResponseCode);

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {
                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                  +" c:/xamp/htdocs/file upload/uploads";
                            messageText.setText(msg);
                            Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

               //close the streams //
               fileInputStream.close();
               dos.flush();
               dos.close();

          } catch (MalformedURLException ex) {

              dialog.dismiss();  
              ex.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
          } catch (Exception e) {

              dialog.dismiss();  
              e.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);  
          }
          dialog.dismiss();       
          return serverResponseCode; 

       } // End else block 
     }}

PHP Server文件上传中的代码,我是通过块完成文件上传的,请谁帮我发送正确的代码文件通过块上传和相关的android文件上传代码

<?php

if (empty($_FILES) || $_FILES['file']['error']) {
die('{"OK": 0, "info": "Failed to move uploaded file."}');
}

$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;

$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = "uploads/$fileName";


// Open temp file
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
//$out2 = @fopen("{$filePath}.part2", $chunk == 0 ? "wb" : "ab");
if ($out) {
// Read binary input stream and append it to temp file
$in = @fopen($_FILES['file']['tmp_name'], "rb");

if ($in) {
while ($buff = fread($in, 4096))
      fwrite($out, $buff);
   //print($out);
 // echo sizeof($out);
} else
die('{"OK": 0, "info": "Failed to open input stream."}');

@fclose($in);

@fclose($out);

@unlink($_FILES['file']['tmp_name']);
} else
die('{"OK": 0, "info": "Failed to open output stream."}');


// Check if file has been uploaded

if (!$chunks || $chunk == $chunks - 1)
{
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}


die('{"OK": 1, "info": "Upload successful."}');?>

共有3个答案

谢建业
2023-03-14

如果您使用的是免费托管,则页面会被重定向以跟踪编号。点击量。您可能会收到Http响应:200 OK,但您不会看到文件上传,因为文件丢失了。

我自己花了3天时间寻找解决方案,但一无所获。我自己发现的。

巫培
2023-03-14

试试这个:它 100% 工作副本。

上传函数:(函数的参数是图像路径)

public void uploadFile(String sourceFileUri) {


          String fileName = imagePath;
          HttpURLConnection conn = null;
          DataOutputStream dos = null;  
          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary = "*****";
          int bytesRead, bytesAvailable, bufferSize;
          byte[] buffer;
          int maxBufferSize = 1 * 1024 * 1024; 
          File sourceFile = new File(imagePath); 

          if (!sourceFile.isFile()) {

                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }

            Log.e("uploadFile", "Source File not exist :"+imagePath);


          }
          else
          {
            try { 

               // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(Upload_Image_URL);

                // Open a HTTP  connection to  the URL
                conn = (HttpURLConnection) url.openConnection(); 
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName); 

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd); 
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                    + fileName + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of  maximum size
                bytesAvailable = fileInputStream.available(); 

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

                while (bytesRead > 0) {

                  dos.write(buffer, 0, bufferSize);
                  bytesAvailable = fileInputStream.available();
                  bufferSize = Math.min(bytesAvailable, maxBufferSize);
                  bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                 }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : " 
                  + serverResponseMessage + ": " + serverResponseCode);


                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

           } catch (MalformedURLException ex) {

                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
               ex.printStackTrace();

               Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
           } catch (Exception e) {

               if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
               }
               e.printStackTrace();


           }

            if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();

            }  


               } // End else block 
             } 

菲律宾语服务:

  $file_path = "images/";
  $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);

  if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
  echo "success";
  } else{ echo "fail";}

必须在服务器中创建名为“images”的文件夹,以便$file_path有效

轩辕奕
2023-03-14

我不知道您的代码,但为您提供两个工作代码:这适用于所有类型的文件。我将其用于图像、音频和视频文件。

Android系统:

new UploadFileAsync().execute("");



  private class UploadFileAsync extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        try {
  String sourceFileUri = "/mnt/sdcard/abc.png";

            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            File sourceFile = new File(sourceFileUri);

            if (sourceFile.isFile()) {

                try {
                    String upLoadServerUri = "http://website.com/abc.php?";

                    // open a URL connection to the Servlet
                    FileInputStream fileInputStream = new FileInputStream(
                            sourceFile);
                    URL url = new URL(upLoadServerUri);

                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true); // Allow Inputs
                    conn.setDoOutput(true); // Allow Outputs
                    conn.setUseCaches(false); // Don't use a Cached Copy
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("ENCTYPE",
                            "multipart/form-data");
                    conn.setRequestProperty("Content-Type",
                            "multipart/form-data;boundary=" + boundary);
                    conn.setRequestProperty("bill", sourceFileUri);

                    dos = new DataOutputStream(conn.getOutputStream());

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
                            + sourceFileUri + "\"" + lineEnd);

                    dos.writeBytes(lineEnd);

                    // create a buffer of maximum size
                    bytesAvailable = fileInputStream.available();

                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];

                    // read file and write it into form...
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                    while (bytesRead > 0) {

                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math
                                .min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0,
                                bufferSize);

                    }

                    // send multipart form data necesssary after file
                    // data...
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens
                            + lineEnd);

                    // Responses from the server (code and message)
                    serverResponseCode = conn.getResponseCode();
                    String serverResponseMessage = conn
                            .getResponseMessage();

                    if (serverResponseCode == 200) {

                        // messageText.setText(msg);
                        //Toast.makeText(ctx, "File Upload Complete.",
                        //      Toast.LENGTH_SHORT).show();

                        // recursiveDelete(mDirectory1);

                    }

                    // close the streams //
                    fileInputStream.close();
                    dos.flush();
                    dos.close();

                } catch (Exception e) {

                    // dialog.dismiss();
                    e.printStackTrace();

                }
                // dialog.dismiss();

            } // End else block


        } catch (Exception ex) {
            // dialog.dismiss();

            ex.printStackTrace();
        }
        return "Executed";
    }

    @Override
    protected void onPostExecute(String result) {

    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

PHP::

 <?php


     if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
    $uploads_dir = './';
                            $tmp_name = $_FILES['bill']['tmp_name'];
                            $pic_name = $_FILES['bill']['name'];
                            move_uploaded_file($tmp_name, $uploads_dir.$pic_name);
                            }
               else{
                   echo "File not uploaded successfully.";
           }

   ?>
 类似资料:
  • 问题内容: 我正在尝试将文件从我的Android设备上传到php服务器,但服务器未收到任何文件。这是我的示例代码,我在线找到了。php服务器,我正在通过块上传文件 我的Android代码 PHP Server代码在文件上传中,我已经完成了通过块进行文件上传,请有人帮助我通过块和相关的android文件上传代码发送正确的代码文件 问题答案: 我不知道您的代码,但是为您提供了两个有效的代码:这适用于所

  • 问题内容: 我正在尝试从Android设备将文件上传到php服务器。有相同问题的话题,但他使用的是不同的方法。我的Android辅助代码运行正常,并且未显示任何错误消息,但服务器未收到任何文件。这是我的示例代码,我在网上找到了。 和我的PHP服务器端代码如下 Apache正在运行。当我运行服务器时,出现此错误消息。上传文件时出错,请重试!我已经在eclipse中检查了日志数据,我认为是套接字问题,

  • 问题内容: 我一直在寻找解决方案,但是已经找不到了。 基本上,我想从Android设备上将文件上传到http网站。但是,我不知道如何执行此操作。我在设备上使用Java,并且我想在服务器端使用PHP。我只想上传文件,而不想在服务器上做任何花哨的事情。 谁能提供代码和/或指向我所需的链接?我对此几乎没有经验,也很茫然。 谢谢,NS PS。我没有PHP编码经验。 问题答案: 是的,所以我找到了Java方

  • 我已经通过Composer下载并安装了谷歌云存储PHP库,下载了JSON密钥文件,但我无法使用该库做任何事情。当我严格按照指示去做时,我只得到错误。不管怎样,这是我试图做任何事情的文件中的代码,比如列表桶文件,或者上传文件,等等...谁能告诉我我做错了什么?我真的很想在我的服务器上使用谷歌云存储来备份文件。 如果这有助于澄清,我正在使用DreamHost VPS作为我的服务器。它支持PHP7.0。

  • 问题内容: 当将大文件(> 100M)上传到服务器时,PHP始终首先接受来自浏览器的全部数据POST。我们无法加入上传过程。 例如,检查的“值”之前整个数据发送到服务器是 不可能的 ,我的PHP代码: 所以我尝试这样使用: map.php 但是…它又失败 了 。在这种情况下工作似乎太晚了。数据仍会完全传输。 然后我尝试了,像这样(代码片段): 结果是…… 再次 失败。 因此,请帮助我找到解决此问题

  • 问题内容: 我想知道是否可以在移动设备(android / iphone / ios)上运行Elasticsearch服务器,如果可以,我应该如何去做。 就我而言,这样做的原因是在设备上拥有一个易于搜索的离线数据库(具有所有elasticsearch高级功能) (可选)我可能还会使用Elasticsearch的集群/复制功能来使设备上的脱机数据与服务器同步。 问题答案: 好吧,也许(至少在Andr