繁体   English   中英

使用android和post方法将图像文件和字符串上传到php后端

[英]Uploading image file and string to php backend using android and post method

我在使用post方法上传图像文件以及字符串时遇到麻烦。 该图像文件实际上确实已上载到服务器,但是我尝试用它发送字符串(用户名)的尝试失败。 我知道我正在获取用户名的值,因为调试时它在日志中显示了用户名。 任何想法就是为什么这不起作用。 这是doInbackground

protected String doInBackground(String... arg0) {
        try {
            String thePic = (String) arg0[0];
            String name = (String) arg0[1];
            String sourceFileUri = thePic;

            Log.d("THENAME",name);
            Log.d("Pic", thePic);
            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())
            {
                Log.d("CheckFile", "Its a file");
                try {
                    String upLoadServerUri = "http://*Myaddress*.com/upload.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("fileToUpload", sourceFileUri);
                    conn.setRequestProperty("Uname", name);


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

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

                    dos.writeBytes(lineEnd);
                    String s = Integer.toString(dos.size());
                    Log.d("DOSFILESIZE", s);

                    // 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)
                    {
                        Log.d("Server Response",serverResponseMessage);

                        // messageText.setText(serverResponseMessage);
                        //Toast.makeText(this, "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();


                            //messageText.setText("Got Exception : see logcat ");
                            //Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",Toast.LENGTH_SHORT).show();
                    Log.e("Upload file to server Exception", "Exception : "+ e.getMessage(), e);
                }
                // dialog.dismiss();

            } // End else block
            else
            {
                Log.d("No image", "Source is not an iamge file");
            }


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

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

这是PHP代码

<?php
$myfile = fopen("userlog.txt", "a");    
fwrite($myfile, "\n\n\n\r\r\n");
fwrite($myfile, "\n\n\n\r\r\n");
fwrite($myfile, date("F j, Y, g:i a") . "\r");
fwrite($myfile, $_SERVER['REMOTE_ADDR']);
fclose($myfile);

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$Uname = $_POST["Uname"];
$status1 = False;
$status2 = False;
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        $uploadOk = 1;
        $con = $con = mysql_connect("localhost:3036","username","password"); 
        if 
        (!$con)
          {
          die('Could not connect: ' . mysql_error());
          }
        mysql_select_db("Rate_It", $con);
        $imgData = file_get_contents($_FILES["fileToUpload"]["tmp_name"]);
        $zero = 0;
        $pid = "NULL";
        $name = "car789";
        $date = "CURDATE()";
        $sql = sprintf("INSERT INTO Picture
        (Pid, Uname, Image, Views, RateTotal, UploadName, UploadDate)
        VALUES
        ('%s', '%s', '%s', '%d', '%d' ,'%s' ,%s)",
        $pid,
        $Uname,
        mysql_real_escape_string($imgData),
        $zero,
        $zero,
        $target_file,
        $date
        );
        $myfile = fopen("test.txt", "a");
        fwrite($myfile, "\n\n\n\r\r\n");
        fwrite($myfile, "\n\n\n\r\r\n");
        fwrite($myfile, date("F j, Y, g:i a"));
        fwrite($myfile, "$sql\n");
        fclose($myfile);
        if ( mysql_query($sql) == TRUE) {
            $status1 = True;
        } 
        else {
            $status1 = False;
        }
        mysql_close($con);

    } else {
        $uploadOk = 0;
    }
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $status2 = True;
    } else {
        $status2 = False;
    }
if($status1 == True && $status2 == True){
    echo "True";
}   
else{
    echo "False";
}

?>

直接之后

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

添加以下代码:

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

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

删除所有带有`Uname'的行,因为那行不起作用。

另外,要抓取页面,PHP脚本将回显,在try块的末尾添加以下代码:

InputStream in = new BufferedInputStream(conn.getInputStream()); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
    sb.append(line + newLine);
  }
String resultPage = sb.toString();

查看您的php脚本,您将收到的不多。 只有“ True”或“ False”;

`

有用。

看起来是这样的:

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

非常感谢您为greenapps提供的信誉。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM