Android上傳文件到服務(wù)端并顯示進(jìn)度條
最近在做上傳文件的服務(wù),簡(jiǎn)單看了網(wǎng)上的教程。結(jié)合實(shí)踐共享出代碼。
由于網(wǎng)上的大多數(shù)沒(méi)有服務(wù)端的代碼,這可不行呀,沒(méi)服務(wù)端怎么調(diào)試呢。
Ok,先上代碼。
Android 上傳比較簡(jiǎn)單,主要用到的是 HttpURLConnection 類,然后加一個(gè)進(jìn)度條組件。
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(); } /** * 開(kāi)始上傳文件 * @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(); //如果有必要?jiǎng)t可以設(shè)置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, 0, mBufferSize); while (mBytesRead > 0) { outputStream.write(buffer, 0, mBufferSize); length += mBufferSize; publishProgress((int) ((length * 100) / mTtotalSize)); mbytesAvailable = fileInputStream.available(); mBufferSize = Math.min(mbytesAvailable, maxBufferSize); mBytesRead = fileInputStream.read(buffer, 0, 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 去上傳文件。代碼比較簡(jiǎn)單,就不一一講解了。
其中要注意的是需要在
將name 設(shè)置為web 請(qǐng)求的參數(shù)名,由于我的服務(wù)端是將文件設(shè)置為file參數(shù),所以我可以直接填file .所以大家可以根據(jù)實(shí)際情況作相應(yīng)修改。
那么接著上服務(wù)端代碼,服務(wù)端主要使用status 2框架作請(qǐng)求。那么我們就需要進(jìn)行封裝。
//上傳文件集合 private List<File> file; //上傳文件名集合 private List<String> fileFileName; //上傳文件內(nèi)容類型集合 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 ,由于是測(cè)試方法。這里就定義為testUpload
public String testUpload()throws Exception{ System.out.println("success"); uploadFile(0); return SUCCESS; }
到這里就已經(jīng)才不多完成動(dòng)作了,現(xiàn)在需要開(kāi)始寫(xiě)上傳的方法 uploadFile(int index),由于定義file 為多文件上傳,而我們上傳只上傳了一個(gè)文件,所以這里參數(shù)為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, 0, length); } in.close(); out.close(); //然后進(jìn)行計(jì)算 return uploadFile.getAbsolutePath(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } return null; }
上面方法為將緩存區(qū)域的文件 然后搞到了D://UploadData/ 文件中,然后以自己的格式進(jìn)行命名,這里我使用了電腦的UUID和文件名進(jìn)行組合,確保我復(fù)制過(guò)來(lái)的文件不重復(fù)。
最后上傳成功之后返回文件的真實(shí)地址。
ok,寫(xiě)到這里上傳文件的功能基本上做完了。最后只剩下配置action 動(dòng)作。
ok,我們打開(kāi)status.xml 文件進(jìn)行配置
<!-- 系統(tǒng)常量定義,定義上傳文件字符集編碼 --> <constant name="struts.i18n.encoding" value="utf-8"></constant> <!-- 系統(tǒng)常量定義,定義上傳文件零時(shí)存放路徑 --> <constant name="struts.multipart.saveDir" value="c:\tmp\"></constant> <constant name="struts.multipart.maxSize" value="10000000" />
這里主要定義上傳文件的臨時(shí)存放位置,然后大小限制。
大家可以根據(jù)實(shí)際情況進(jìn)行配置。
最后上傳一張效果圖。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Android ProgressDialog用法之實(shí)現(xiàn)app上傳文件進(jìn)度條轉(zhuǎn)圈效果
- Android Volley擴(kuò)展實(shí)現(xiàn)支持進(jìn)度條的文件上傳功能
- Android實(shí)現(xiàn)文件上傳和下載倒計(jì)時(shí)功能的圓形進(jìn)度條
- Android帶進(jìn)度條的文件上傳示例(使用AsyncTask異步任務(wù))
- Android頁(yè)面中引導(dǎo)蒙層的使用方法詳解
- Android實(shí)現(xiàn)新手引導(dǎo)半透明蒙層效果
- Android 新手引導(dǎo)蒙層效果實(shí)現(xiàn)代碼示例
- Android實(shí)現(xiàn)圖片上傳蒙層進(jìn)度條
相關(guān)文章
Android 菜單欄DIY實(shí)現(xiàn)效果詳解
這篇文章主要為大家介紹了Android 菜單欄DIY實(shí)現(xiàn)效果詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Android仿微博加載長(zhǎng)圖滾動(dòng)查看效果
這篇文章主要為大家詳細(xì)介紹了Android仿微博加載長(zhǎng)圖滾動(dòng)查看效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-12-12Android開(kāi)發(fā)實(shí)現(xiàn)模仿360二維碼掃描功能實(shí)例詳解
這篇文章主要介紹了Android開(kāi)發(fā)實(shí)現(xiàn)模仿360二維碼掃描功能,結(jié)合實(shí)例形式詳細(xì)分析了Android開(kāi)發(fā)二維碼掃描功能所涉及的zxing開(kāi)源項(xiàng)目文件使用方法及具體掃碼功能相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-10-10Android多線程斷點(diǎn)續(xù)傳下載示例詳解
這篇文章主要為大家詳細(xì)介紹了Android多線程斷點(diǎn)續(xù)傳下載示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11Android實(shí)現(xiàn)在列表List中顯示半透明小窗體效果的控件用法詳解
這篇文章主要介紹了Android實(shí)現(xiàn)在列表List中顯示半透明小窗體效果的控件用法,結(jié)合實(shí)例形式分析了Android半透明提示框的實(shí)現(xiàn)與設(shè)置技巧,需要的朋友可以參考下2016-06-06Android 多層嵌套后的 Fragment 懶加載實(shí)現(xiàn)示例
這篇文章主要介紹了Android 多層嵌套后的 Fragment 懶加載實(shí)現(xiàn)示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04Android?Jetpack結(jié)構(gòu)運(yùn)用Compose實(shí)現(xiàn)微博長(zhǎng)按點(diǎn)贊彩虹效果
Compose在動(dòng)畫(huà)方面下足了功夫,提供了豐富的API。但也正由于API種類繁多,如果想一氣兒學(xué)下來(lái),最終可能會(huì)消化不良,導(dǎo)致似懂非懂。結(jié)合例子學(xué)習(xí)是一個(gè)不錯(cuò)的方法,本文就帶大家邊學(xué)邊做,通過(guò)實(shí)現(xiàn)一個(gè)微博長(zhǎng)按點(diǎn)贊的動(dòng)畫(huà)效果,學(xué)習(xí)了解Compose動(dòng)畫(huà)的常見(jiàn)思路和開(kāi)發(fā)技巧2022-07-07Android 實(shí)現(xiàn)錨點(diǎn)定位思路詳解
本篇文章就使用tablayout、scrollview來(lái)實(shí)現(xiàn)android錨點(diǎn)定位的功能。通過(guò)<a href="#head" rel="external nofollow" > 去設(shè)置頁(yè)面內(nèi)錨點(diǎn)定位跳轉(zhuǎn)。具體實(shí)現(xiàn)思路大家跟隨腳本之家小編一起通過(guò)本文看下吧2018-07-07