使用Android和放上传图片; PHP [英] Upload image using android & php

查看:264
本文介绍了使用Android和放上传图片; PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上传图片使用PHP在服务器上而是在特定的文件夹。

I'm trying to upload image on server but in specific folder using 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);
?>

这是我怎么发送图片:

And this is how I'm sending image:

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

    }

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

The part that I don't understand is how to send parameter that is reserved for creating subfolder on server.

推荐答案

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

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

Where String subfolder contains the subfolder name.

在PHP端就可以在正常的方式使用 $子文件夹= $解压_ POST ['子'];

At php side you can extract it in the normal way with $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);
?>

修改如果(RES code == HttpURLConnection.HTTP_OK) //如果(RES code == HttpURLConnection类。 HTTP_OK)

这篇关于使用Android和放上传图片; PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆