Android上传下载文件(图片)

这里写是Android下上传下载文件,需要服务器端相应的程序配合,使用的是POST方法。Android客户端代码如下:


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class NetFileGetPost {
	
	/**
	 * 从服务器读取文件
	 * @param path    文件保存的路径
	 * @param urlPath 文件在服务器的位置
	 * @return
	 * @throws Exception
	 */
	public static Bitmap readFromUri(String path, String urlPath)
			throws Exception {
		Log.d("debug","start read pic " + urlPath);
		URL url = new URL(urlPath);
		byte[] d = null;

		/**
		 * 建立连接
		 */
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(3 * 1000);

		/**
		 * 得到连接状态
		 */
		int code = conn.getResponseCode();
		Log.d("debug","code = " + code);
		if (code == 200) {

			/**
			 * 首先得到输入流,然后从输入流中写出数据到一个byte数组中,利用BitmapFactory工厂方法通过字节数组来得到
			 * 一个bitmap对象,最后利用FileOutputStream将bitmap对象转化成一个.png图片,存放在PIC_PATH中
			 */
			InputStream in = conn.getInputStream();
			d = readStream(path, in);
			if (d == null) {
				Log.w("debug","PicUtils --- >>> d == null");
				return null;
			}
			Bitmap bit = BitmapFactory.decodeByteArray(d, 0, d.length);
			File file = new File(path);
			if (!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream out = new FileOutputStream(file);
			bit.compress(Bitmap.CompressFormat.JPEG, 100, out);
			conn.disconnect();
			out.close();
			in.close();
			return bit;
		} else {
			Log.w("debug","get Image is wrong");
		}
		return null;
	}
	
	
	private static byte[] readStream(String path, InputStream inStream) throws Exception {
        if (!createFile(path)) {
            Log.e("debug","create file path is not allow");
            return null;
        }
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inStream.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }
        outstream.close();
        return outstream.toByteArray();
    }
	
	/**
	 * 创建文件
	 */
	private static boolean createFile(String path) {
		File file = new File(path);
		
		if (file.exists()) {
			file.delete();
		}
		
		try {
			file.createNewFile();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}


	/** 
	 * 上传文件到服务器
     * @param urlPath  网络地址 
     * @param picPath  该图片所在文件夹位置 
     * @功能 上传图片,我的服务端是是用php写的 
     */  
  
    public static String uploadPic(String urlPath, String picPath) {  
        DataOutputStream dos = null;    // 往服务端写入数据的输出流  
        
        try {  
            Log.d("debug","start upload pic " + urlPath);  
            String end = "\r\n";    // 前面这些都是写html文件的头文件,固定的,不用去管  
            String twoHyphens = "--";  
            String boundary = "*****";
            URL url = new URL(urlPath);  
            HttpURLConnection httpURLConnection = (HttpURLConnection) url  
                    .openConnection();
            httpURLConnection.setChunkedStreamingMode(20 * 1024);// 文件大小20K
            httpURLConnection.setDoInput(true);  
            httpURLConnection.setDoOutput(true);  
            httpURLConnection.setUseCaches(false);  // 这个地方不使用缓存  
            httpURLConnection.setRequestMethod("POST");  
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");  
            httpURLConnection.setRequestProperty("Charset", "UTF-8");  
            httpURLConnection.setRequestProperty("Content-Type",  
                    "multipart/form-data;boundary=" + boundary);  
            dos = new DataOutputStream(httpURLConnection.getOutputStream());  
            dos.writeBytes(twoHyphens + boundary + end);  
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""  
                    + picPath.substring(picPath.lastIndexOf("/") + 1)  
                    + "\";"  
                    + end);  
            dos.writeBytes(end);  
            FileInputStream fis = new FileInputStream(picPath);  
            byte[] buffer = new byte[1024 * 2];  
            int count = 0;  
            while ((count = fis.read(buffer)) != -1) {  
                dos.write(buffer, 0, count);  
            }  
            fis.close();
            dos.writeBytes(end);  
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);  
            dos.flush();  
  
  
            BufferedReader reader = new BufferedReader(new InputStreamReader(  
                    httpURLConnection.getInputStream()));  
            String result = reader.readLine();  // 这个是得到上传图片的结果  
            Log.d("debug","PicUtils --- >>> result = " + result);  
            reader.close();  
            httpURLConnection.disconnect();  
            return result;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        } finally {  
            if (dos != null) {  
                try {  
                    dos.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    } 
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值