Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Android上传文件到服务端并显示进度条大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

最近在做上传文件的服务,简单看了网上的教程。结合实践共享出代码

由于网上的大多数没有服务端的代码,这可不行呀,没服务端怎么调试呢。

Ok,先上代码

Android 上传比较简单,主要用到的是 httpURLConnection 类,然后加一个进度条组件。

private ProgressBar mPgBar; 
class UploadTask extends AsyncTask<Object,Integer,Void>{ 
  private DataOutputStream outputStream = null; 
  private String filename; 
  private String uri; 
  private String mLineEnd = "\r\n"; 
  private String mTwoHyphens = "--"; 
  private String boundary = "*****"; 
  File uploadFile ; 
  long mT@R_136_10586@lSize ; // Get size of file,bytes 
  public UploadTask(String filename,String uri){ 
   this.filename = filename; 
   thiS.Uri = uri; 
   uploadFile= new File(fileName); 
    mT@R_136_10586@lSize = uploadFile.length(); 
  } 
 
  /** 
   * 开始上传文件 
   * @param objects 
   * @return 
   */ 
  @Override 
  protected Void doInBACkground(Object... objects) { 
   long length = 0; 
   int mBytesRead,mbytesAvailable,mBufferSize; 
   byte[] buffer; 
   int maxBufferSize = 256 * 1024;// 256KB 
   try{ 
 
    FileInputStream fileInputStream = new FileInputStream(new File(fileName)); 
 
    URL url = new URL(uri); 
 
    httpURLConnection con = (httpURLConnection) url.openConnection(); 
 
    //如果有必要则可以设置Cookie 
//    conn.setrequestProperty("Cookie","JSESSIONID="+cookiE); 
 
    // Set size of every block for post 
 
    con.setChunkedStreamingMode(256 * 1024);// 256KB 
 
    // Allow Inputs & Outputs 
    con.setDoInput(true); 
    con.setDoOutput(true); 
    con.setUseCaches(false); 
 
    // Enable POST method 
    con.setrequestMethod("POST"); 
    con.setrequestProperty("Connection","Keep-Alive"); 
    con.setrequestProperty("Charset","UTF-8"); 
    con.setrequestProperty("Content-Type","multipart/form-data;boundary=" + boundary); 
 
    outputStream = new DataOutputStream( 
      con.getOutputStream()); 
    outputStream.writeBytes(mTwoHyphens + boundary + mLineEnd); 
    outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"" + mLineEnd); 
    outputStream.writeBytes("Content-Type:application/octet-stream \r\n"); 
    outputStream.writeBytes(mLineEnd); 
 
    mbytesAvailable = fileInputStream.available(); 
    mBufferSize = Math.min(mbytesAvailable,maxBufferSizE); 
    buffer = new byte[mBufferSize]; 
 
    // Read file 
    mBytesRead = fileInputStream.read(buffer,mBufferSizE); 
 
    while (mBytesRead > 0) { 
     outputStream.write(buffer,mBufferSizE); 
     length += mBufferSize; 
 
     publishProgress((int) ((length * 100) / mT@R_136_10586@lSizE)); 
 
     mbytesAvailable = fileInputStream.available(); 
 
     mBufferSize = Math.min(mbytesAvailable,maxBufferSizE); 
 
     mBytesRead = fileInputStream.read(buffer,mBufferSizE); 
    } 
    outputStream.writeBytes(mLineEnd); 
    outputStream.writeBytes(mTwoHyphens + boundary + mTwoHyphens 
      + mLineEnd); 
    publishProgress(100); 
 
    // Responses from the server (code and messagE) 
    int serverResponseCode = con.getResponseCode(); 
    String serverResponsemessage = con.getResponsemessage(); 
    fileInputStream.close(); 
    outputStream.flush(); 
    outputStream.close(); 
 
   } catch (Exception eX) { 
    ex.printStackTrace(); 
    Log.v(tag,"uploadError"); 
   } 
   return null; 
  } 
 
  @Override 
  protected void onProgressupdate(Integer... progress) { 
   mPgBar.setProgress(progress[0]); 
  } 
 } 

主要流程为继承AsyncTask,然后使用httpURLConnection 去上传文件代码比较简单,就不一一讲解了。
其中要注意的是需要在

outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" +  filename + "\"" + mLineEnd); 

将name 设置为web 请求的参数名,由于我的服务端是将文件设置为file参数,@R_794_9447@直接填file .所以大家可以根据实际情况作相应修改

那么接着上服务端代码,服务端主要使用status 2框架作请求。那么我们就需要进行封装。

//上传文件集合 
 private List<File> file; 
 //上传文件名集合 
 private List<String> fileFilename; 
 //上传文件内容类型集合 
 private List<String> fileContentType; 
 
 public List<File> getFile() { 
  return file; 
 } 
 
 public void setFile(List<File> filE) { 
  this.file = file; 
 } 
 
 public List<String> getFileFilename() { 
  return fileFilename; 
 } 
 
 public void setFileFilename(List<String> fileFileName) { 
  this.fileFilename = fileFilename; 
 } 
 
 public List<String> getFileContentType() { 
  return fileContentType; 
 } 
 
 public void setFileContentType(List<String> fileContentTypE) { 
  this.fileContentType = fileContentType; 
 } 

采用了多文件上传方法,定义了List 集合。
那么处理文件上传的action,由于是测试方法。这里就定义为testupload

public String testupload()throws Exception{ 
  System.out.println("success"); 
  uploadFile(0); 
  return succesS; 
 } 

到这里就已经才不多完成动作了,现在需要开始写上传方法 uploadFile(int indeX),由于定义file 为多文件上传,而我们上传上传一个文件,所以这里参数为0

/** 
  * 上传功能 
  * @param i 
  * @return 
  * @throws FileNotFoundException 
  * @throws IOException 
  */ 
 private String uploadFile(int i) throws FileNotFoundException,IOException { 
   
  try { 
   InputStream in = new FileInputStream(file.get(i)); 
 
   //String dir = ServletActionContext.getrequest().getRealPath(UPLOADDIR); 
    
   String dir = "D://UploadData/"; 
 
   File uploadFile = new File(dir,StringUtils.getUUID()+getFile( this.getFileFilename().get(i))); 
 
   OutputStream out = new FiLeoutputStream(uploadFilE); 
 
   byte[] buffer = new byte[1024 * 1024]; 
 
   int length; 
   while ((length = in.read(buffer)) > 0) { 
    out.write(buffer,length); 
   } 
 
   in.close(); 
   out.close(); 
   //然后进行计算 
   return uploadFile.getAbsolutePath(); 
  } catch (FileNotFoundException eX) { 
   ex.printStackTrace(); 
  } catch (IOException eX) { 
   ex.printStackTrace(); 
  } 
  return null; 
 } 

上面方法为将缓存区域的文件 然后搞到了D://UploadData/ 文件中,然后以自己的格式进行命名,这里我使用了电脑的UUID和文件名进行组合,确保我复制过来的文件不重复。
最后上传成功之后返回文件的真实地址。

ok,写到这里上传文件功能基本上做完了。最后只剩下配置action 动作。

ok,我们打开status.xml 文件进行配置

<!-- 系统常量定义,定义上传文件字符集编码 --> 
 <constant name="struts.i18n.encoding" value="utf-8"></constant> 
 <!-- 系统常量定义,定义上传文件零时存放路径 --> 
 <constant name="struts.multipart.saveDir" value="c:\tmp\"></constant> 
 <constant name="struts.multipart.maxSize" value="10000000" /> 

这里主要定义上传文件的临时存放位置,然后大小限制。
大家可以根据实际情况进行配置

最后上传一张效果图。

Android上传文件到服务端并显示进度条

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

大佬总结

以上是大佬教程为你收集整理的Android上传文件到服务端并显示进度条全部内容,希望文章能够帮你解决Android上传文件到服务端并显示进度条所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。