欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

基于标准http实现Android多文件上传

程序员文章站 2024-02-22 13:33:04
实现多文件的上传,基于标准的http来实现。 1.多文件上传myuploader类的实现: /** * * 同步上传多个文件 * 基于标准...

实现多文件的上传,基于标准的http来实现。

1.多文件上传myuploader类的实现:

/**
 * 
 * 同步上传多个文件
 * 基于标准的http实现,需要在非ui线程中调用,以免阻塞ui。
 *
 */
public class myuploader {
 private static final string tag = "myuploader";

 // ////////////////////同步上传多个文件/////////
  /**
   * 同步上传file
   * 
   * @param url
   * @param fullfilename
   *   : 全路径,ex. /sdcard/f/yh.jpg
   * @param filename
   *   : file name, ex. yh.jpg
   * @return 服务器的响应结果(字符串形式)
   */
  public string myuploadmultifilesync(string url,
    list<string> filelist, map<string, string> params) {
   string reulstcode = "";
   string end = "\r\n";
   string twohyphens = "--";
   string boundary = "--------boundary";

   try {
    url url = new url(actionurl);
    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",
    // "application/x-www-form-urlencoded");
    con.setrequestproperty("content-type",
      "multipart/form-data;boundary=" + boundary);

    stringbuffer s = new stringbuffer();
    // 设置dataoutputstream
    dataoutputstream dos = new dataoutputstream(con.getoutputstream());

    for (int i = 0; i < filelist.size(); i++) {

     string filepath = filelist.get(i);

     int endfileindex = filepath.lastindexof("/");
     string filename = filepath.substring(endfileindex + 1);
     log.i(tag, "filename= " + filename);
     // set 头部
     stringbuilder sb = new stringbuilder();

     sb.append(twohyphens);
     sb.append(boundary);
     sb.append(end);
     sb.append("content-disposition: form-data; ");
     sb.append("name=" + "\"" + "upload_file" +i + "\"");
     sb.append(";filename=");
     sb.append("\"" + filename + "\"");
     sb.append(end);

     sb.append("content-type: ");
     sb.append("image/jpeg");
     sb.append(end);
     sb.append(end);

     // 1. write sb
     dos.writebytes(sb.tostring());

     // 取得文件的fileinputstream
     fileinputstream fis = new fileinputstream(filepath);
     // 设置每次写入1024bytes
     int buffersize = 1024;
     byte[] buffer = new byte[buffersize];

     int length = -1;
     // 从文件读取数据至缓冲区
     while ((length = fis.read(buffer)) != -1) {
      dos.write(buffer, 0, length);
     }
     dos.writebytes(end);
     fis.close();

     dos.writebytes(end);
     dos.writebytes(end);

     //dos.writebytes(end);
     //dos.flush();
     // close streams
     //fis.close();
    }

    // set 尾部
    stringbuilder sb2 = new stringbuilder();

    if (params != null && !params.isempty()) {
     for (string key : params.keyset()) {
      string value = params.get(key);
      sb2.append(twohyphens);
      sb2.append(boundary);
      sb2.append(end);
      sb2.append("content-disposition: form-data; ");
      sb2.append("name=" + "\"");
      sb2.append(key + "\"");
      sb2.append(end);
      sb2.append(end);
      sb2.append(value);
      sb2.append(end);
     }
    }
    sb2.append(twohyphens + boundary + end);
    dos.writebytes(sb2.tostring());
    dos.flush();
    log.i(tag, "sb2:" + sb2.tostring());

    // 取得response内容
    inputstream is = con.getinputstream();
    int ch;
    stringbuffer b = new stringbuffer();
    while ((ch = is.read()) != -1) {
     b.append((char) ch);
    }
    reulstcode = b.tostring().trim();
    // 关闭
    dos.close();
   } catch (ioexception e) {
    log.i(tag, "ioexception: " + e);
    e.printstacktrace();
   }

   return reulstcode;
  }
}

2. 调用方法:

由于myuploader的myuploadmultifilesync本身是同步的函数请求,所以,这个函数需要在非ui线程中执行。本例采用thread+handler的方式来进行说明。
下面是activity的主要代码,功能是将cache目录中的的jpg文件上传到指定的服务器:

public void uploadthreadtest() {
  new thread(new runnable() {
   @override
   public void run() {

    try {
     upload();
    } catch (exception e) {
     e.printstacktrace();
    }
   }

  }).start();

 }

 private void upload() {
  string url = "https://httpbin.org/post";
  list<string> filelist = getcachefiles();

  if (filelist == null) {
   myhandler.sendemptymessage(-1);
  }else {
   myuploader myupload = new myuploader();
   //同步请求,直接返回结果,根据结果来判断是否成功。
   string reulstcode = myupload.myuploadmultifilesync(url, filelist, null);
   log.i(tag, "upload reulstcode: " + reulstcode);
   myhandler.sendemptymessage(0);

  }
 }

 private list<string> getcachefiles() {
  list<string> filelist = new arraylist<string>();
  file catchpath = mcontext.getcachedir();

  if (catchpath!=null && catchpath.isdirectory()) {

   file[] files = catchpath.listfiles();
   if (files == null || files.length<1) {
    return null;
   }
   for (int i = 0; i < files.length; i++) {
    if (files[i].isfile() && files[i].getabsolutepath().endswith(".jpg")) {
     filelist.add(files[i].getabsolutepath());
    }

   }
   return filelist;

  }
  return null;


 }
 ////////////handler/////
 private handler myhandler = new handler() {
  @override
  public void handlemessage(message msg) {
   log.i(tag,"handlemessage msg===" + msg);
   if (msg.what == -1) {
    toast.maketext(mcontext, "not find file!", toast.length_long).show();
    return;
   }else {
    toast.maketext(mcontext, "upload success!", toast.length_long).show();
   }

  }

 };

3 项目demo代码地址:https://github.com/ranke/httpasynctest

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。