您的位置:首页 > 理论基础 > 计算机网络

Android Http上传文件 PHP接收

2015-12-24 19:08 393 查看

Client

创建HttpURLConnection,并设置属性(相当于请求头),其中最后一句最重要,multipart/form-data定义了是“文件上传”,boundary=*定义了分割线(人造POST格式要求非常严格!!)

URL url = new URL(uploadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setChunkedStreamingMode(128 * 1024);
hconnection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=*******");


然后是请求体,一定要注意格式!!

- -boundry //表示开始(两个横线中间空格去掉!!)

Content-Disposition: form-data; name=\”file\”; filename=\”asd.jpg\”” //name要跟PHP中$_FILES[‘??’]一样!!filename会赋值给PHP中的$_FILES[‘??’][‘name’]

file的字节¥#……¥%&……%&%&%&

- -boundry- - //表示结束(两个横线中间空格去掉!!)

DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes("--" + "*******" + end);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"asd.jpg\"" + end);
dos.writeBytes(end);

FileInputStream fis = new FileInputStream(path);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes("--" + "*******" + "--" + end);
dos.flush();


最后接收响应结果

InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReade
4000
r(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = "";
String line;
while ((line = br.readLine()) != null){
result += line;
}
System.out.println(result);
dos.close();
is.close();


Servlet

只要设置了multipart/form-data,上传文件会被自动接收到一个临时文件夹,脚本结束时自动删除,所有的相关属性可以通过$_FILES读到。想永久保存,要用move_uploaded_file()函数,第一个参数是$_FILES [‘file’] [‘tmp_name’],第二个参数是$_FILES [‘file’] [‘name’](这个可以变,一般用这个,Servlet文件名和Client保持一致,前面还可以加个文件夹比如”./uploads/”,但是必须提前新建它)。

$_FILES[‘file’][‘error’]用于输出错误。

$_FILES[“userfile”][“size”]上传文件的大小。

$_FILES[“userfile”][“type”]上传文件的类型,用于验证类型。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: