PHP如何响应移动端(android or ios)的post请求(使用file_get_contents)

来源:互联网 发布:python turtle填色 编辑:程序博客网 时间:2024/04/25 15:07

file_get_contents这个函数是PHP在处理http请求时接受移动端数据的非常重要的一个方法

他的作用是把整个文件读入一个字符串中。


file_get_contents(path,include_path,context,start,max_length)

参数描述path必需。规定要读取的文件。include_path可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 "1"。context

可选。规定文件句柄的环境。

context 是一套可以修改流的行为的选项。若使用 null,则忽略。

start可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 新加的。max_length可选。规定读取的字节数。该参数是 PHP 5.1 新加的。

所以对于一个移动端上传一个文件的请求,以android为例子:

private static final int BUFFER = 2048;private void testPost() {String url = "http://2.novelread.sinaapp.com/framework-sae/index.php?c=main&a=getPostBodyAndContent";DefaultHttpClient client = null;HttpRequestBase http = null;HttpResponse response = null;ByteArrayOutputStream outStream = null;byte data[] = new byte[BUFFER];try {http = new HttpPost(url);//在手机SD上有一张11.jpg的图片File f = new File(Environment.getExternalStorageDirectory(), "11.jpg");long length = f.length();//发给服务端的数据使用byte的格式outStream = new ByteArrayOutputStream();BufferedInputStream in_buf_stream = null;//先写入文件(11.jpg)的大小String s = String.valueOf(length);s = String.format("%08d", length);outStream.write(s.getBytes());//再写入11.jpgin_buf_stream = new BufferedInputStream(new FileInputStream(f), BUFFER);int count;while ((count = in_buf_stream.read(data, 0, BUFFER)) != -1) {outStream.write(data, 0, count);}ByteArrayEntity att_byte = null;if (outStream != null) {att_byte = new ByteArrayEntity(outStream.toByteArray());try {if (outStream != null) {outStream.close();outStream = null;}} catch (Throwable th) {}//用setEntity的方式写到http请求中((HttpEntityEnclosingRequestBase) http).setEntity(att_byte);}DefaultHttpClient httpClient = RestHttpClient.getClient().getHttpClient();response = httpClient.execute(http);int code = response.getStatusLine().getStatusCode();if (code == HttpStatus.SC_OK) {HttpEntity respEntity = response.getEntity();InputStream inputStream = respEntity.getContent();StringBuilder builder = new StringBuilder();InputStreamReader Inreader = new InputStreamReader(inputStream);BufferedReader reader = new BufferedReader(Inreader);String line;try {while ((line = reader.readLine()) != null) {builder.append(line).append("\n");}} finally {try {reader.close();} catch (IOException e) {}}}try {if (att_byte != null) {att_byte.consumeContent();att_byte = null;}} catch (Throwable th) {}} catch (ClientProtocolException e) {} catch (Exception e) {}    }

这个post请求是先写入文件大小,然后才是文件的内容,这个时候PHP这边

$raw .= file_get_contents('php://input');

这里$raw就存储了客户端传来的entity里的以byte方式存储的数据

然后我们需要分割这些数据:

$length = substr($raw,0,8);
$content = substr($raw,8,$length);

这样我们就得到文件的内容$content,我们可以把这个内容保存成一个文件,这里是保存在sae的domain上面,'file'是我的domain名称,我在'file'上创建了一个文件夹test

 <span style="white-space:pre"></span> $storage = new SaeStorage(); $domain = 'file'; $destFileName = "/test/".$img_name; $result = $storage->write($domain,$destFileName, $content, -1,$attr,false); echo $result;


0 0