服务端代码:
<?php
if(move_uploaded_file($_FILES['file']['tmp_name'], "./upload/".$_FILES["file"]["name"])) {
echo "success";
} else {
echo "fail";
};
客户端代码:
package com.zhym.friendcircule;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.zhym.myapp.R;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by lenovo on 2015/9/11.
*/
public class Test extends Activity{
private String fileName = "20151102203744.jpg";
private String uploadFile = "/sdcard/DCIM/Camera/20151102203744.jpg";
private String actionUrl = "http://10.108.218.249/myown/proctice.php";
private TextView mText1;
private TextView mText2;
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
mText1 = (TextView) findViewById(R.id.test1); //文件路径
mText2 = (TextView) findViewById(R.id.test2); //上传网址
mText1.setText(uploadFile);
mText2.setText(actionUrl);
mButton = (Button) findViewById(R.id.mButton);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadFile();
}
});
}
//上传文件至Server的方法
private void uploadFile() {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
URL url = new URL(actionUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//允许Input、Output,不使用Cache
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
//设置传送的method=POST
con.setRequestMethod("POST");
//setRequestProperty
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
//设置StrictMode,否则HttpURLConnection连接失败,因为这是在主线程中进行网络连接
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
//设置DataOutputStream
DataOutputStream dos = new DataOutputStream(con.getOutputStream());
dos.writeBytes(twoHyphens+boundary+end);
dos.writeBytes("Content-Disposition: form-data; " +
"name=\"file\";filename=\"" +
fileName + "\"" + end);
dos.writeBytes(end);
Log.e("", "*******************3333333333333");
//取得文件的FileInputStream
FileInputStream fis = new FileInputStream(uploadFile);
int bufferSize = 8192;
byte[] buffer = new byte[bufferSize];
int length = -1;
while((length = fis.read(buffer)) != -1) { //从文件读取数据至缓冲区
dos.write(buffer, 0, length);
}
dos.writeBytes(end);
dos.writeBytes(twoHyphens+boundary+twoHyphens+end);
fis.close(); //关闭流,写入的东西自动生成Http正文
dos.flush();
//获取Response内容
InputStream is = con.getInputStream(); //HTTP请求设置完成,con.getInputStream()中会将请求(HTTP头+HTTP正文)发送到服务器,并返回一个输入流。
//从返回的输入流中读取相应消息
int ch;
StringBuffer b = new StringBuffer();
while((ch=is.read()) != -1) {
b.append((char) ch);
}
/* 显示网页响应内容 */
// Toast.makeText(Test.this, b.toString().trim(), Toast.LENGTH_SHORT).show();//Post成功
showDialog("上传成功"+b.toString().trim());
dos.close();
} catch (Exception e) {
/* 显示异常信息 */
Toast.makeText(Test.this, "Fail:" + e, Toast.LENGTH_SHORT).show();//Post失败
e.printStackTrace();
}
}
private void showDialog(String mess) {
new AlertDialog.Builder(Test.this).setTitle("Message")
.setMessage(mess)
.setNegativeButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
}