首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

URL 文件下传的原理

2012-10-25 
URL 文件上传的原理?phpfunction upload_curl_pic(){$url? http://localhost//5-5-5//uploadfile.php

URL 文件上传的原理

<?php
function upload_curl_pic()
{
$url? = 'http://localhost//5-5-5//uploadfile.php';? //target url
$file = 'c:/21.jpg'; //要上传的文件
$fields['f'] = '@'.$file;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields );
curl_exec( $ch );
if ($error = curl_error($ch) ) {
?????? die($error);
}
curl_close($ch);?
}
upload_curl_pic();//可以扩展把图片地址传到函数中
?>


接收端:
<?php
$uploaddir = 'E:\\wwwroot\\www\\htdocs\\5-5-5\\pic_all_here\\';
$uploadfile = $uploaddir . $_FILES['f']['name'];
if (move_uploaded_file($_FILES['f']['tmp_name'], $uploadfile))
{?
??? echo "File is valid, and was successfully uploaded.\n";
} else {
??????????? echo "Possible file upload attack!\n";
??????????? echo 'Here is some more debugging info:';
?????????

?????? }

?>

android上面图片的上传可以用apache包里面的httpclient和MultipartEntity来上传图片,这种的上传方式的话由于都封装好了所以看不到HTTP协议里面具体是怎样上传的;
其实图片的上传还可以用Java自带的HttpURLConnection来做上传处理,例如有一个PHP写的接收图片的POST接口http://localhost/upload/upload.php
img[] 图片(支持多张图片上传)

<?php
??? echo $_POST["name"];
??? echo $_POST["address"];
??????????????????????????????????????????????????????????????????
??? $img = $_FILES['img'];
??? if ($img){
??????? //文件存放目录,和本php文件同级
??????? $dir = dirname(__file__);
??????? $i = 0;
??????? foreach ($img['tmp_name'] as $value){
??????????? $filename = $img['name'][$i];
??????????? if ($value){
??????????????? $savepath="$dir\\$filename";
??????????????? $state = move_uploaded_file($value, $savepath);
??????????????? //如果上传成功,预览
??????????????? if($state){
??????????????????? echo $filename." upload success";
??????????????? }
??????????? }
??????????? $i++;
??????? }
??? }
?>


这时假如我们上传的参数为:
name值为this is the parameter:name
address值为this is the parameter:address
img[]的值为两张图片,路径为E:\Photos\test_1.jpg 和E:\Photos\test_2.jpg
那么我们写的POST网络请求的方法体应该为下面的格式:
-----------------------------7dc2fd5c0894
Content-Disposition: form-data; name="name"
this is the parameter:name
-----------------------------7dc2fd5c0894
Content-Disposition: form-data; name="address"
this is the parameter:address
-----------------------------7dc2fd5c0894
Content-Disposition: form-data; name="img[]"; filename="E:\Photos\test_1.jpg"
Content-Type: image/pjpeg

<图片E:\Photos\test_1.jpg的二进制数据未显示>
---------------------------7dc2fd5c0894
Content-Disposition: form-data; name="img[]"; filename="E:\Photos\test_2.jpg"
Content-Type: image/pjpeg
<图片E:\Photos\test_2.jpg的二进制数据未显示 >
-----------------------------7dc2fd5c0894--

根据上面的格式我们写的上传图片的Java代码如下:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
????????????????????????????????????
public class Main {
????????????????????????????????????
??? public static void main(String[] args) {
??????? List<String> list = new ArrayList<String>();
??????? list.add("E:\\Photos\\test_1.jpg");//要上传的文件路径
??????? list.add("E:\\Photos\\test_2.jpg");//要上传的文件路径
????????????????????????????????????
??????? upload("this is the parameter:name", "this is the parameter:address",
??????????????? list);
??? }
????????????????????????????????????
??? public static void upload(String name, String address, List<String> list) {
????????????????????????????????????
??????? try {
??????????? // 定义数据分隔线
??????????? String BOUNDARY = "------------------------7dc2fd5c0894";
??????????? // 定义最后数据分隔线
??????????? byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
????????????????????????????????????
??????????? URL url = new URL("http://localhost/upload/upload.php");
??????????? HttpURLConnection conn = (HttpURLConnection) url.openConnection();
????????????????????????????????????
??????????? conn.setDoOutput(true);
??????????? conn.setDoInput(true);
??????????? conn.setUseCaches(false);
??????????? conn.setRequestMethod("POST");
??????????? conn.setRequestProperty("connection", "Keep-Alive");
??????????? conn.setRequestProperty("user-agent",
??????????????????? "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");
??????????? conn.setRequestProperty("Charsert", "UTF-8");
??????????? conn.setRequestProperty("Content-Type",
??????????????????? "multipart/form-data; boundary=" + BOUNDARY);
????????????????????????????????????
??????????? OutputStream out = new DataOutputStream(conn.getOutputStream());
????????????????????????????????????
??????????? // name参数
??????????? StringBuffer params = new StringBuffer();
??????????? params.append("--" + BOUNDARY + "\r\n");
??????????? params.append("Content-Disposition: form-data; name="name"\r\n\r\n");
??????????? params.append(name);
??????????? params.append("\r\n");
????????????????????????????????????
??????????? // address参数
??????????? params.append("--" + BOUNDARY + "\r\n");
??????????? params.append("Content-Disposition: form-data; name="address"\r\n\r\n");
??????????? params.append(address);
??????????? params.append("\r\n");
????????????????????????????????????
??????????? out.write(params.toString().getBytes());
????????????????????????????????????
??????????? int leng = list.size();
??????????? for (int i = 0; i < leng; i++) {
??????????????? String fname = list.get(i);
??????????????? File file = new File(fname);
????????????????????????????????????
??????????????? StringBuilder sb = new StringBuilder();
??????????????? sb.append("--");
??????????????? sb.append(BOUNDARY);
??????????????? sb.append("\r\n");
??????????????? sb.append("Content-Disposition: form-data;name="img[]";filename=""
??????????????????????? + file.getName() + ""\r\n");
??????????????? // 这里不能漏掉,根据文件类型来来做处理,由于上传的是图片,所以这里可以写成image/pjpeg
??????????????? sb.append("Content-Type:image/pjpeg\r\n\r\n");
??????????????? out.write(sb.toString().getBytes());
????????????????????????????????????
??????????????? DataInputStream in = new DataInputStream(new FileInputStream(
??????????????????????? file));
??????????????? int bytes = 0;
??????????????? byte[] bufferOut = new byte[1024];
??????????????? while ((bytes = in.read(bufferOut)) != -1) {
??????????????????? out.write(bufferOut, 0, bytes);
??????????????? }
??????????????? out.write("\r\n".getBytes());
??????????????? in.close();
??????????? }
??????????? out.write(end_data);
??????????? out.flush();
??????????? out.close();
????????????????????????????????????
??????????? // 定义BufferedReader输入流来读取URL的响应
??????????? BufferedReader reader = new BufferedReader(new InputStreamReader(
??????????????????? conn.getInputStream()));
??????????? String line = null;
??????????? while ((line = reader.readLine()) != null) {
??????????????? System.out.println(line);
??????????? }
????????????????????????????????????
??????? } catch (Exception e) {
??????????? System.out.println("发送POST请求出现异常!" + e);
??????????? e.printStackTrace();
??????? }
??? }
????????????????????????????????????
}
这样就可以把多张图片和参数上传到服务器了。当然这里只是一个演示,是用php写的接口并只是简单的把图图片保存在了接口文件的当前文件夹下;另外图片也没有做压缩,android手机上面上传时一般会做压缩,而且也不会一个接口上传多张图片,网络差时给用户的体验很不好,但是对于互联网开发者来说深入理解HTTP协议对表单是怎样处理的这个还是很重要

热点排行