您的位置:首页 > 移动开发 > Android开发

Android 上传/下载图片

2015-05-22 13:28 423 查看
/**
* 上传图片到服务器
* @param uploadFile 要上传的文件目录
* @param actionUrl 上传的地址
* @return String
*/
public static HashMap<String, Object> uploadFile(String actionUrl,Drawable drawable){
Log.info(TAG, "urlPath= " + actionUrl);

String end ="\r\n";
String twoHyphens ="--";
String boundary ="*****";

HttpURLConnection con = null;
DataOutputStream ds = null;
InputStream is = null;
StringBuffer sb = null;
HashMap<String, Object> map = null;

try{
URL url =new URL(actionUrl);
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 */
ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "+ "name=\"file1\";filename=\""+ MyAppActivity.FILENAME +"\""+ end);
ds.writeBytes(end);

if(drawable != null){
Bitmap bitmap = drawableToBitmap(drawable);
byte[] buffer = Bitmap2Bytes(bitmap);
ds.write(buffer);
}

ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
ds.flush();
/* 取得Response内容 */

Log.info(TAG, "code= " + con.getResponseCode());
if(con.getResponseCode() == 200){
is = con.getInputStream();

int ch;
sb =new StringBuffer();
while( ( ch = is.read() ) !=-1 ){
sb.append( (char)ch );
}
ds.close();

Log.info(TAG, "sb= " + sb.toString());
if(!sb.toString().equals("") || sb.toString() != null){
map = new HashMap<String, Object>();
map = JsonUtil.parseJSON(sb.toString());
}
}

}catch (MalformedURLException e) {
Log.info("json","url error");
e.printStackTrace();
} catch(FileNotFoundException e){
Log.info("json","file not found");
}catch (IOException e) {
Log.info("json","io error");
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
if(ds != null){
ds.close();
}
if(is != null){
is.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return map;
}

/**
* drawable转换为bitamp
*/
private static Bitmap drawableToBitmap(Drawable drawable) {
// 取 drawable 的长宽
int w = drawable.getIntrinsicWidth();
int h = drawable.getIntrinsicHeight();

// 取 drawable 的颜色格式
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565;
// 建立对应 bitmap
Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// 建立对应 bitmap 的画布
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, w, h);
// 把 drawable 内容画到画布中
drawable.draw(canvas);
return bitmap;
}

private static byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}

public static void downLoadImage(String urlPath){
String fileName = urlPath.substring(urlPath.lastIndexOf('/')+1,urlPath.length());//提取下载图片的文件名
Bitmap bitmap=GetNetBitmap(urlPath);//得到bitmap
File file = new File(MyAppActivity.DIRPATH);
if(!file.exists()){
file.mkdir();
}

File file2 = new File(MyAppActivity.DIRPATH,fileName);
if(!file2.exists()){
//将网络上读取的图片保存到SDCard中
try {
FileOutputStream out=new FileOutputStream(new File(MyAppActivity.DIRPATH, fileName));//为图片文件实例化输出流
if(bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)){//对图片保存
out.flush();
Log.info("json","Success");
out.close();
}
}catch (FileNotFoundException e) {
// TODO: handle exception
Log.info("json","文件没发现!!");
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
Log.info("json","数据流错误!!");
}
}
}

/**
* 取得网络上的图片
* @param url 图片的URL
*/
@SuppressWarnings("unused")
private static Bitmap GetNetBitmap(String url){
URL imageUrl = null;
Bitmap bitmap=null;
try {
imageUrl = new URL(url);
}
catch (MalformedURLException e) {
e.printStackTrace();
}

if (imageUrl != null) {
try {
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setDoInput(true);// 设置请求的方式
conn.connect();

InputStream is = conn.getInputStream();// 将得到的数据转化为inputStream
bitmap = BitmapFactory.decodeStream(is);// 将inputstream转化为Bitmap
is.close();// 关闭数据
} catch (IOException e) {
e.printStackTrace();
}
}
else{
Log.info("json", "json is null!!!");
}
return bitmap;
}

/**
* 上传图片
* @param uploadFile 要上传的文件目录
* @param actionUrl 上传的地址
* @return String
*/
public static String uploadFile(String uploadFile,String actionUrl){
String end ="\r\n";
String twoHyphens ="--";
String boundary ="*****";

HttpURLConnection con = null;
DataOutputStream ds = null;
FileInputStream fStream = null;
InputStream is = null;
StringBuffer sb = null;

try{
URL url =new URL(actionUrl);
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 */
ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "+ "name=\"file1\";filename=\""+ MyAppActivity.FILENAME +"\""+ end);
ds.writeBytes(end);
/* 取得文件的FileInputStream */
if(uploadFile != null){
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 */
ds.flush();
/* 取得Response内容 */
is = con.getInputStream();
int ch;
sb =new StringBuffer();
while( ( ch = is.read() ) !=-1 ){
sb.append( (char)ch );
}
ds.close();
}catch (MalformedURLException e) {
Log.info("json","url error");
e.printStackTrace();
} catch(FileNotFoundException e){
Log.info("json","file not found");
}catch (IOException e) {
Log.info("json","io error");
e.printStackTrace();
}finally{
try{
if(ds != null){
ds.close();
}
if(is != null){
is.close();
}
if(fStream != null){
fStream.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: