可传参数的图片上传

1.上传图片的类

public class HttpFile { 
 String  BOUNDARY =  UUID.randomUUID().toString();  //边界标识   随机生成
 String CONTENT_TYPE = "multipart/form-data";   //内容类型
    URL url; 
    HttpURLConnection conn; 
    String boundary = "--------httppost123"; 
    Map<String, String> textParams = new HashMap<String, String>(); 
    Map<String, File> fileparams = new HashMap<String, File>(); 
    DataOutputStream ds; 
 
    public HttpFile(String url) throws Exception { 
        this.url = new URL(url); 
    } 
    //重新设置要请求的服务器地址,即上传文件的地址。 
    public void setUrl(String url) throws Exception { 
        this.url = new URL(url); 
    } 
    //增加一个普通字符串数据到form表单数据中 
    public void addTextParameter(String name, String value) { 
        textParams.put(name, value); 
    } 
    //增加一个文件到form表单数据中 
    public void addFileParameter(String name, File value) { 
        fileparams.put(name, value); 
    } 
    // 清空所有已添加的form表单数据 
    public void clearAllParameters() { 
        textParams.clear(); 
        fileparams.clear(); 
    } 
    // 发送数据到服务器,返回一个字节包含服务器的返回结果的数组 
    public byte[] send() throws Exception { 
        initConnection(); 
        try { 
            conn.connect(); 
        } catch (SocketTimeoutException e) { 
            // something 
            throw new RuntimeException(); 
        } 
        ds = new DataOutputStream(conn.getOutputStream()); 
        writeFileParams(); 
        writeStringParams(); 
        paramsEnd(); 
        InputStream in = conn.getInputStream(); 
        ByteArrayOutputStream out = new ByteArrayOutputStream(); 
        int b; 
        while ((b = in.read()) != -1) { 
            out.write(b); 
        } 
        conn.disconnect(); 
        return out.toByteArray(); 
    } 
    //文件上传的connection的一些必须设置 
    private void initConnection() throws Exception { 
        conn = (HttpURLConnection) this.url.openConnection(); 
        conn.setDoOutput(true); 
        conn.setUseCaches(false); 
        conn.setConnectTimeout(10000); //连接超时为10秒 
        conn.setRequestMethod("POST"); 
        conn.setRequestProperty("Content-Type", 
                "multipart/form-data; boundary=" + boundary); 
    } 
    //普通字符串数据 
    private void writeStringParams() throws Exception { 
        Set<String> keySet = textParams.keySet(); 
        for (Iterator<String> it = keySet.iterator(); it.hasNext();) { 
            String name = it.next(); 
            String value = textParams.get(name); 
            ds.writeBytes("--" + boundary + "\r\n"); 
            ds.writeBytes("Content-Disposition: form-data; name=\"" + name 
                    + "\"\r\n"); 
            ds.writeBytes("\r\n"); 
            ds.writeBytes(encode(value) + "\r\n"); 
        } 
    } 
    //文件数据 
    private void writeFileParams() throws Exception { 
        Set<String> keySet = fileparams.keySet(); 
        for (Iterator<String> it = keySet.iterator(); it.hasNext();) { 
            String name = it.next(); 
            File value = fileparams.get(name); 
            ds.writeBytes("--" + boundary + "\r\n"); 
            ds.writeBytes("Content-Disposition: form-data; name=\"" + name 
                    + "\"; filename=\"" + encode(value.getName()) + "\"\r\n"); 
            ds.writeBytes("Content-Type: " + CONTENT_TYPE + ";boundary=" + BOUNDARY + "\r\n"); 
            ds.writeBytes("\r\n"); 
            ds.write(getBytes(value)); 
            ds.writeBytes("\r\n"); 
        } 
    } 
    //获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream 
    //把文件转换成字节数组 
    private byte[] getBytes(File f) throws Exception { 
        FileInputStream in = new FileInputStream(f); 
        ByteArrayOutputStream out = new ByteArrayOutputStream(); 
        byte[] b = new byte[1024]; 
        int n; 
        while ((n = in.read(b)) != -1) { 
            out.write(b, 0, n); 
        } 
        in.close(); 
        return out.toByteArray(); 
    } 
    //添加结尾数据 
    private void paramsEnd() throws Exception { 
        ds.writeBytes("--" + boundary + "--" + "\r\n"); 
        ds.writeBytes("\r\n"); 
    } 
    // 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码 
    private String encode(String value) throws Exception{ 
        return URLEncoder.encode(value, "UTF-8"); 
    } 
}

2.代码中使用

   //上传图片的服务器地址
   HttpFile u = new HttpFile(
     "http://192.168.3.189:8081/rest/file/upload");
   //上传图片的图片位置
   u.addFileParameter("file", fi);
   //上传的参数
   u.addTextParameter("userId",
     PreferenceHelper.readString(ac, "freight", "userId"));
   //得到的结果
   byte[] b = u.send();
   //转化为字符串
   String result = new String(b);
   //gson解析
   Gson gson = new Gson();
   CarUrl carUrl = gson.fromJson(result, CarUrl.class);

3.在代码中使用,需要放到子线程中

 private Runnable r;
 private Handler mHandler;

 HandlerThread thread = new HandlerThread("Myhandler");
  thread.start();// 创建一个HandlerThread并启动它
  mHandler = new Handler(thread.getLooper()) {
   @Override
   public void handleMessage(Message msg) {
    // TODO Auto-generated method stub
    super.handleMessage(msg);
    switch (msg.what) {
    case 100:
     Log.d("back", "上传成功");
     loadad.dismiss();
     mHandler.removeCallbacks((Runnable) msg.obj);
     break;
    default:
     break;
    }
   }
  };// 使用HandlerThread的looper对象创建Handler,如果使用默认的构造方法,很有可能阻塞UI线程



    r = new Runnable() {

     @Override
     public void run() {
      // TODO Auto-generated method stub
      Message msg = mHandler.obtainMessage();
       msg.what = 100;
       msg.obj = r;
       mHandler.sendMessage(msg);

     }
    };
    mHandler.post(r);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值