php用于上传调用的文件,但文件未存储

时间:2014-03-19 18:28:55

标签: php android upload

我正在尝试将.png文件上传到我的服务器。 php被调用并返回,但文件从未上传。我的代码中必须有一些小故障,但我找不到它。

Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
if(myBitmap!=null){
    pixels = new byte[myBitmap.getWidth() * myBitmap.getHeight()];
    for (int i = 0; i < myBitmap.getWidth(); ++i) {
        for (int j = 0; j < myBitmap.getHeight(); ++j) {
            pixels[i + j] = (byte) ((myBitmap.getPixel(i, j) & 0x80) >> 7);
        }
    }
}
HttpURLConnection connectionWWW = (HttpURLConnection) url.openConnection();
connectionWWW.setChunkedStreamingMode(0);//3.0
connectionWWW.setReadTimeout(100000);
String boundary =  "*****"; 
String attachmentFileName = "screenshot.png";
String crlf = "\r\n";
String twoHyphens = "--";

if(imgFile.exists()){
    connectionWWW.setUseCaches(false);//3.0
    connectionWWW.setDoOutput(true);
    connectionWWW.setDoInput(true);
    connectionWWW.setRequestMethod("POST");
    connectionWWW.setRequestProperty("Connection", "Keep-Alive");

    connectionWWW.setRequestProperty("ENCTYPE", "multipart/form-data");
    connectionWWW.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
    connectionWWW.setRequestProperty("uploaded_file", attachmentFileName);

    DataOutputStream request = new DataOutputStream(connectionWWW.getOutputStream());

    request.writeBytes(twoHyphens + boundary + crlf);

    request.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"" + attachmentFileName + "\"" + crlf);
    request.writeBytes(crlf);

    request.write(pixels);

    request.writeBytes(crlf);
    request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
    request.flush();
    request.close();
}

in = new BufferedInputStream(connectionWWW.getInputStream());

String res = convertStreamToString(in);

connectionWWW.disconnect();//3.0

php:

$uploaddir = './android/';
$file = basename($_FILES['uploaded_file']['name']);
$filet = basename($_FILES['uploaded_file']['tmp_name']);
$uploadfile = $uploaddir . $file;
$rec="/android/".$file;
echo $rec;

$ rec总是回答“./android” - $ file为空

2 个答案:

答案 0 :(得分:3)

如果您尚未使用move_uploaded_file()功能,请尝试以下操作。

这就是使用PHP上传文件的方式。另外,t

中有$filet
$filet = basename($_FILES['uploaded_file']['tmp_name']);

所以可能就是这样。

看看是否有效:

$file_path = "./android/"; // assuming running code from root

$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {

    $uploadfile = $uploaddir . $file_path;
    $rec="/android/".$file_path;
    echo $rec;

    echo "success";
} else{
    echo "fail";
}

另外,请确保该文件夹具有正确的写入权限。

<强>脚注:

我不确定/android/./android/其中一个可能需要更改才能相互反映。

答案 1 :(得分:0)

最后,它表明问题出在Java代码中。 我用POST删除了部分并重新创建了它,然后瞧!有用。 在连接参数中某处可能存在一个看不见的杂散符号,如图所示。

感谢任何人试图提供帮助。