求android开发中的实现上传与下载的代码,最好可以给个完整教程
发布网友
发布时间:2022-06-02 03:45
我来回答
共1个回答
热心网友
时间:2023-10-27 16:19
下载图片核心代码:
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bitmap=null;
try{
URL url=new URL(params[0]);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.connect();
int MAX=connection.getContentLength();
InputStream inputStream=connection.getInputStream();
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte []buf=new byte[1024];
int len=0;
while((len=inputStream.read(buf))!=-1){
outputStream.write(buf, 0, len);
}
bitmap=BitmapFactory.decodeByteArray(outputStream.toByteArray(), 0, MAX);
inputStream.close();
}catch(Exception e){
//TODO
System.out.println("loading images failed");
}
return bitmap;
}
上传图片核心代码:
private void uploadFile()
{
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try
{
URL url =new URL(actionUrl+"upload");
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);
/* 设置DataOutputStream */
DataOutputStream ds =
new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; " +
"name=\"file1\";filename=\"" +
reg_username.getText().toString()+".jpg" +"\"" + end);
ds.writeBytes(end);
imageView.buildDrawingCache();
Bitmap bmp = imageView.getDrawingCache();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] content=baos.toByteArray();
ds.write(content, 0, content.length);
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
ds.flush();
/* 取得Response内容 */
InputStream is = con.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while(( ch = is.read())!= -1 )
{
b.append((char)ch );
}
JSONObject object=new JSONObject(b.toString());
if(TextUtils.equals(object.getString("message"), "ok")){
upload_flag=true;
}else{
upload_flag=false;
}
/* 关闭DataOutputStream */
ds.close();
}
catch(Exception e)
{
upload_flag=false;
}
}