用戶端Android和Webservice之間的圖片檔案傳輸解決方案

來源:互聯網
上載者:User

標籤:des   android   blog   io   ar   os   java   on   檔案   

最近在寫webservice介面 給用戶端提供資料和接收用戶端發來的資料。當資料類型為圖片類型的檔案時候,先把檔案轉為流,然後用Base64編碼成位元組流的字串,傳輸的還是字串。

用戶端代碼:

public static void main(String[] args) throws IOException { File file=new File("d:/272.jpg");     FileInputStream fis = new FileInputStream(file);     ByteArrayOutputStream baos = new ByteArrayOutputStream();       byte[] buffer = new byte[1024];           int count = 0;           while((count = fis.read(buffer)) >= 0){               baos.write(buffer, 0, count);           }           String uploadBuffer = new String(Base64.encode(baos.toByteArray()));  //進行Base64編碼           fis.close();           writeSmilFile(uploadBuffer);System.out.println("uploadBuffer:"+uploadBuffer);}//寫到txtpublic static void writeSmilFile(String content) {File file1 = new File( "d:/123.txt");try {file1.createNewFile();} catch (IOException e) {e.printStackTrace();}PrintWriter pw;try { OutputStreamWriter os = null; os = new OutputStreamWriter(new FileOutputStream(file1),"UTF-8");  os.write(content);        os.close();} catch (IOException e) {e.printStackTrace();}}

伺服器端代碼:
//擷取用戶端傳來的圖片檔案 (  用戶端處理是檔案轉換為流  Base64編碼成字串)public String getPhotoByAndroid(String photoPath){//圖片存放路徑 放到正式需要修改String newFilePath="D:/";String newFileName =UUID.randomUUID().toString()+"jpg"; FileOutputStream fos = null;        byte[] buffer;try {buffer = new BASE64Decoder().decodeBuffer(photoPath); //對android傳過來的圖片字串進行解碼           File destDir = new File(newFilePath);            if(!destDir.exists()) destDir.mkdir();          fos = new FileOutputStream(new File(destDir,newFileName));   //儲存圖片          fos.write(buffer);          fos.flush();          fos.close();         } catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}         System.out.println("上傳圖片成功!" + newFilePath+newFileName);   return newFileName;}


用戶端Android和Webservice之間的圖片檔案傳輸解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.