我正在尝试将 .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 是空的
最佳答案
如果您还没有使用 move_uploaded_file()
,请尝试以下操作功能。
这就是使用 PHP 上传文件的方式。另外你在 $filet
t
$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/
其中之一可能需要更改以反射(reflect)彼此相同。
关于用于上传文件的 php 已调用,但文件未存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22515005/