【发布时间】:2014-03-19 18:28:54
【问题描述】:
我正在尝试将 .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 是空的
【问题讨论】:
-
$_FILES中是否有任何东西? -
我做了一个 var_dump($_FILES);显示文件 count=0 array(0) { }
-
你没有使用
move_uploaded_file()函数吗? @michaelsmith 这就是使用 PHP 上传文件的方式。另外,您在$filet和$filet = basename($_FILES['uploaded_file']['tmp_name']);中有一个t,可能就是这样。将其更改为$file = basename($_FILES['uploaded_file']['tmp_name']);