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

标签 php android image post upload

我在使用 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 block 的末尾添加以下代码:

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 脚本,您将收到的信息不多。只有“真”或“假”;

`

关于php - 使用android和post方法将图像文件和字符串上传到php后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29930404/

相关文章:

php - mysqli bind_param() fatal error

android - 当我在文本框中键入一些文本时,OnKey 事件分派(dispatch)了两次。如何预防?

Android - 尝试添加图像时会创建一个空白图像

Android 5.0 Lollipop 无法正确显示特殊字符

javascript - Jvectormap 将图像添加到特定标签

java - Swing GUI 中的储 jar 液位指示器图像

php - 处理由于引入类型提示而导致的 PHP 致命类型错误

php - reCAPTCHA 集中对齐

PHP报告按钮

android - 从画廊kitkat android中选择图像时检索绝对路径