
最近在做上传文件的服务,简单看了网上的教程。结合实践共享出代码。
由于网上的大多数没有服务端的代码,这可不行呀,没服务端怎么调试呢。
Ok,先上代码。
AndroID 上传比较简单,主要用到的是 httpURLConnection 类,然后加一个进度条组件。
@H_403_8@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 mTtotalSize ; // Get size of file,bytes public UploadTask(String filename,String uri){ this.filename = filename; this.uri = uri; uploadfile= new file(filename); mTtotalSize = 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) / mTtotalSize)); 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参数,所以我可以直接填file .所以大家可以根据实际情况作相应修改。
那么接着上服务端代码,服务端主要使用status 2框架作请求。那么我们就需要进行封装。
@H_403_8@//上传文件集合 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 文件进行配置
@H_403_8@<!-- 系统常量定义,定义上传文件字符集编码 --> <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上传文件到服务端并显示进度条所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)