我有一个用HTTPPost方法上传到用PHP编写的Web服务器的图像。我的代码将位图压缩为jpeg编码的字节数组,并将Base64编码的位图发送到服务器,服务器对其进行解码,将其写入文件并将其打开为jpg图像。
Index.hp:
<?php
$base=$_REQUEST['image'];
echo $base;
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');
// print($binary);
//$theFile = base64_decode($image_data);
$file = fopen('test.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo '<img src=test.jpg>';
?>
我在同一个目录中有一个空的0kb test.jpg。
有时,当我快速按F5(刷新)时,我可以看到图像,但当我再次刷新时,图像会再次被删除,并且再次为0KB。(在谷歌Chrome上工作)
1) 我如何才能使图片保持显示写入test.jpg的数据,而不变回0kb?所以当我看到它的时候,照片仍然在那里。(注意,我的PHP知识不是很好,所以非常感谢说明。)
JAVA,Android的上传方法:
public void uploadFrame(byte[] Frame, String WebClient) {
String ba1=Base64.encodeBytes(mCurrentFrame);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost(WebClient);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
2) 另一个问题是,这种方法是否真的是安全的,因为人们可以向它发送任何POST方法数据并显示任何图片。那么,在PHP中如何首先检查JAVA中的参数是否等于PHP代码中的参数,这样只有具有相同参数的人才能将此代码上传到他的Web服务器。
对于一些人来说,这可能是一个非常有趣的话题。
编辑:
<?php
if (isset($_REQUEST['image'])) {
$base=$_REQUEST['image'];
echo $base;
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');
// print($binary);
//$theFile = base64_decode($image_data);
$file = fopen('test.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
echo '<img src=test.jpg>';
}
header('Content-type: image/jpeg');
readfile('test.jpg');
?>
每次刷新页面时,它都会将数据写入test.jpg
文件。如果你不提交一个base64映像,它只会写出一个空白/null字符串,这意味着一个0字节的文件。
相反,试试这个:
<?php
if (isset($_REQUEST['image'])) {
... your decoding/fopen/fwrite stuff here ...
}
header('Content-type: image/jpeg')
readfile('test.jpg');
这将直接将图像输出为jpg,而不是输出HTML并强制浏览器打开另一个HTTP连接来加载.jpg文件。
回答问题2:
不,它不安全。你真的应该在传输过程中签名或直接加密它,以确保你可以信任你得到的数据——它要么是你的,要么是垃圾。查看mcrypt()
了解更多信息。
快速警告:如果您将标题设置为位图,请不要在屏幕上写入HTML:(echo '<img src=test.jpg>';
)
我会将标题回显为image/jpeg
,然后将原始二进制文件写入屏幕。