Chinaunix首页 | 论坛 | 博客
  • 博客访问: 474463
  • 博文数量: 155
  • 博客积分: 2954
  • 博客等级: 少校
  • 技术积分: 1000
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-12 22:00
文章分类

全部博文(155)

文章存档

2014年(2)

2013年(5)

2012年(10)

2011年(33)

2010年(105)

我的朋友

分类: Java

2010-05-05 14:59:02

public void upload() {
    String name = po.getName(); // file name
    String str = po.getStr()+"/plugins/j2me"; // url
    byte[] raw = snap.getData(); // file data
    String cmd = "uploadpic";
    String auth = po.getUserId();
    String albumId = po.getUserId();
    String type = po.getType();
    String remarks = po.getDemo();
    String[] props = { "cmd","auth","albumId", "public", "remarks" }; //property name
    String[] values = { cmd, auth, albumId, type, remarks }; // property value
    try {
        String BOUNDARY = "---------7d4a6d158c9"; // separate line
        String MULTIPART_FORM_DATA = "multipart/form-data";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < props.length; i++) { // send each property
            sb = sb.append("--");
            sb = sb.append(BOUNDARY);
            sb = sb.append("\r\n");
            sb = sb.append("Content-Disposition: form-data; name=\""+ props[i] + "\"\r\n\r\n");
            sb = sb.append(URLEncoder.encode(values[i],"UTF-8"));
            sb = sb.append("\r\n");
        }
        sb = sb.append("--");
        sb = sb.append(BOUNDARY);
        sb = sb.append("\r\n");
        sb = sb.append("Content-Disposition: form-data;name=\"file\";filename=\""+ name + ".jpg\"\r\n");
        sb = sb.append("Content-Type: application/octet-stream\r\n\r\n");
        byte[] data = sb.toString().getBytes();
        byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
        HttpConnection hc = (HttpConnection) Connector.open(str,Connector.READ_WRITE); // set HTTP head:
        hc.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
        hc.setRequestProperty("Content-Length", String.valueOf(data.length+ raw.length + end_data.length)); //
//        hc.setRequestProperty("Connection", "keep-alive");
        hc.setRequestMethod(HttpConnection.POST); // out: OutputStream                                            //
        output =hc.openOutputStream();
        output.write(data);
        output.write(raw, 0, raw.length);
        output.write(end_data);
        int cah = hc.getResponseCode();
        if (cah != HttpConnection.HTTP_OK) {
            System.out.println(cah);
            return;
        }
        output.close();
        //receive(hc);
        hc.close();
    } catch (IOException e) {
    } catch (SecurityException e) {
    } catch (NullPointerException e) {
    }
}

阅读(463) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~