public class ex08_11 extends activity
{
/* 变量声明
* newname:上传后在服务器上的文件名称
* uploadfile:要上传的文件路径
* actionurl:服务器对应的程序路径 */
// private string newname=345444.jpg;
private string uploadfile=/sdcard/345444.jpg;
private string acti//*********/upload.php;
private textview mtext1;
private textview mtext2;
private button mbutton;
@override
public void oncreate(bundle savedinstancestate)
{
super.oncreate(savedinstancestate);
setcontentview(r.layout.main);
mtext1 = (textview) findviewbyid(r.id.mytext2);
mtext1.settext(文件路径:\n+uploadfile);
mtext2 = (textview) findviewbyid(r.id.mytext3);
mtext2.settext(上传网址:\n+actionurl);
/* 设定mbutton的onclick事件处理 */
mbutton = (button) findviewbyid(r.id.mybutton);
mbutton.setonclicklistener(new view.onclicklistener()
{
public void onclick(view v)
{
uploadfile();
}
});
}
/* 上传文件吹server的method */
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.setreadtimeout(5 * 1000);
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(enctype,
multipart/form-data;boundary=+boundary);
/* 设定dataoutputstream */
dataoutputstream ds =
new dataoutputstream(con.getoutputstream());
/*ds.writebytes(twohyphens + boundary + end);
ds.writebytes(content-disposition: form-data; +
name=\file1\;filename=\ +
newname +\ + end);
ds.writebytes(end); */
/* 取得文件的fileinputstream */
fileinputstream fstream = new fileinputstream(uploadfile);
/* 设定每次写入1024bytes */
int buffersize = 1024;
byte[] buffer = new byte[buffersize];
int length = -1;
/* 从文件读取数据到缓冲区 */
while((length = fstream.read(buffer)) != -1)
{
/* 将数据写入dataoutputstream中 */
ds.write(buffer, 0, length);
}
// ds.writebytes(end);
// ds.writebytes(twohyphens + boundary + twohyphens + end);
/* close streams */
fstream.close();
ds.flush();
/* 取得response内容 */
inputstream is = con.getinputstream();
int ch;
stringbuffer b =new stringbuffer();
while( ( ch = is.read() ) != -1 )
{
b.append( (char)ch );
}
/* 将response显示于dialog */
showdialog(b.tostring().trim());
/* 关闭dataoutputstream */
ds.close();
}
catch(exception e)
{
showdialog(+e);
}
}
/* 显示dialog的method */
private void showdialog(string mess)
{
new alertdialog.builder(ex08_11.this).settitle(message)
.setmessage(mess)
.setnegativebutton(确定,new dialoginterface.onclicklistener()
{
public void onclick(dialoginterface dialog, int which)
{
}
})
.show();
}
}
php代码
以上就介绍了android 上传图片到php服务器,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
