【问题标题】:Upload image using android & php使用android和php上传图片
【发布时间】:2015-04-30 11:39:53
【问题描述】:

我正在尝试使用 php 在服务器上上传图像,但在特定文件夹中。

这是 PHP 脚本:

<?php   

$subfolder = $_POST['subfolder'];
mkdir($subfolder, 0755, true);

if(@move_uploaded_file($_FILES["filUpload"]["tmp_name"],"upload/".$subfolder.$_FILES["filUpload"]["name"]))
{
    $arr["StatusID"] = "1";
    $arr["Error"] = "";
}
else
{
    $arr["StatusID"] = "0";
    $arr["Error"] = "Cannot upload file.";
}

echo json_encode($arr);
?>

这就是我发送图像的方式:

//Upload
    public void startUpload() {     

        Runnable runnable = new Runnable() {

            public void run() {


                handler.post(new Runnable() {
                    public void run() {

                        new UploadFileAsync().execute();    
                    }
                });

            }
        };
        new Thread(runnable).start();
    }

     // Async Upload
    public class UploadFileAsync extends AsyncTask<String, Void, Void> {

        String resServer;


        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String... params) {
            // TODO Auto-generated method stub

            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            int resCode = 0;
            String resMessage = "";

            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary =  "*****";


            String strSDPath = selImgPath;

            // Upload to PHP Script
            String strUrlServer = "http://localhost/zon/uploadFile.php";

            try {
                /** Check file on SD Card ***/
                File file = new File(strSDPath);
                if(!file.exists())
                {
                    resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
                    return null;
                }

                FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));

                URL url = new URL(strUrlServer);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");

                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);


                DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("");


                outputStream.writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\"" + file.getName().toString() + "\"" + lineEnd);
                outputStream.writeBytes(lineEnd);


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

                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }

                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Response Code and  Message
                resCode = conn.getResponseCode();
                if(resCode == HttpURLConnection.HTTP_OK)
                {
                    InputStream is = conn.getInputStream();
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();

                    int read = 0;
                    while ((read = is.read()) != -1) {
                          bos.write(read);
                    }
                    byte[] result = bos.toByteArray();
                    bos.close();

                    resMessage = new String(result);                        

                }

                fileInputStream.close();
                outputStream.flush();
                outputStream.close();

                resServer = resMessage.toString();

                System.out.println("RES MESSAGE = " + resMessage.toString());

            } catch (Exception ex) {            
                return null;
            }

            return null;
        }

        protected void onPostExecute(Void unused) {
            // statusWhenFinish(position,resServer);
        }

    }

我不明白的部分是如何发送为在服务器上创建子文件夹而保留的参数。

【问题讨论】:

  • 您不能在该行中传递额外的参数。但是,您可以根据需要发布任意数量的 key=value 参数。使用它们将子文件夹告诉 php 脚本。
  • 我不知道该怎么做?这是我第一次使用这种方法。你有这方面的例子吗?
  • 上传图片时,记得将表单的 ENCTYPE 设置为 `multipart/form-data´。
  • new UploadFileAsync().execute(); 这应该是startUpload. 中唯一的语句删除所有其他代码。您不需要该线程,因为 AsyncTask 已经是一个线程。

标签: php android file-upload


【解决方案1】:

之后

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

添加以下行:

        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"subfolder\"" + lineEnd);
        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(subfolder + lineEnd);

其中字符串子文件夹包含子文件夹名称。

在 php 端,您可以使用 $subfolder=$_POST['subfolder']; 以正常方式提取它

编辑:

将您的脚本更改为:

<?php   
error_reporting( E_ALL );
ini_set('display_errors', '1');

var_dump($_POST);
print_r($_FILES);

if ( ! isset($_POST['subfolder']) )
{
echo ("Sorry no 'subfolder' in POST array.\n");
exit();
}

$subfolder = $_POST['subfolder'];

$targetpath = "upload/" . $subfolder;

echo ( "subfolder: ". $subfolder . "\n");
echo ( "targetpath: ". $targetpath . "\n");

if ( ! file_exists( $targetpath ) )
 {
if ( ! mkdir( $targetpath, 0755, true) )
    echo ("error could not mkdir(): " . $targetpath . "\n");
else
    echo ("mkdir() created: " . $targetpath . "\n");
}

if(move_uploaded_file($_FILES["filUpload"]["tmp_name"], $targetpath . "/". $_FILES["filUpload"]["name"]))
{
$arr["StatusID"] = "1";
$arr["Error"] = "";
}
else
{
$arr["StatusID"] = "0";
$arr["Error"] = "Cannot upload file.";
}

echo json_encode($arr);
?>

if(resCode == HttpURLConnection.HTTP_OK) 更改为//if(resCode == HttpURLConnection.HTTP_OK)

【讨论】:

  • 如果您需要帮助,您应该提供更多信息。例如,您的 php 脚本。更重要的是:会发生什么?
  • 查看更新了我的第一篇文章。我已经粘贴了用于将图像发送到服务器的代码并修改了 PHP 脚本。
  • 请在您的帖子中添加我的代码行,因为 php 脚本现在正在徒劳地等待“子文件夹”..
  • 一般来说,您应该在脚本中添加更多的 echo() 以查看实际发生的情况。否则你就瞎了。
  • 我试过了,但还是没有。在输出中我得到错误:注意:未定义的索引:第 21 行 /var/www/zon/uploadFile.php 中的 filUpload。也没有创建子文件夹。子文件夹变量的内容是正确定义的,在回显输出中我可以看到它。我也有权在上传文件夹中写入,所以这不是问题。
【解决方案2】:

试试这个方法..它对我有用..

      FileInputStream fileInputStream = new FileInputStream(sourceFile);
               URL url = new URL(upLoadServerUri);
               System.out.println(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("image_1", imgs);


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

                 // add parameters
                 dos.writeBytes(twoHyphens + boundary + lineEnd);
                 dos.writeBytes("Content-Disposition: form-data; name=\"type\""
                         + lineEnd);
                 dos.writeBytes(lineEnd);

                 // assign value


                 // send image
                 dos.writeBytes(twoHyphens + boundary + lineEnd); 
                 dos.writeBytes("Content-Disposition: form-data; name='image_1';filename='"
                         + imgs + "'" + 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() {
                        @SuppressWarnings("deprecation")
                        public void run() {


                            try 
                            {


                                DataInputStream dataIn = new DataInputStream(conn.getInputStream());
                                String inputLine;
                                while ((inputLine = dataIn.readLine()) != null) 
                                {
                                    result += inputLine;
                                    System.out.println("Result : " + result);
                                }
                                //result=getJSONUrl(url);  //<< get json string from server
                                //JSONObject jsonObject = new JSONObject(result);
                                JSONObject jobj = new JSONObject(result);
                                sta = jobj.getString("status");
                                msg = jobj.getString("msg");
                                System.out.println(sta + " >>>>>>> " + msg);


                            } 
                            catch (Exception e) 
                            {
                                e.printStackTrace();
                            }


                        }
                    });                
               }    

【讨论】:

  • 我发布的代码完美无缺,但我只想通过代码更改上传文件夹。例如,根文件夹是上传,但我也希望能够在上传文件夹的子文件夹中上传文件。
  • 'conn.setRequestProperty("image_1", imgs);'你能解释一下这个声明的作用吗? “imgs”的价值是什么。检索此信息的 php 代码是什么?
猜你喜欢
  • 2011-08-03
  • 2015-06-14
  • 2015-01-17
  • 2010-12-06
  • 2011-11-14
  • 2014-12-02
  • 2016-08-10
  • 2016-11-03
  • 2019-04-05
相关资源
最近更新 更多