客戶端Android和Webservice之間的圖片檔案傳輸解決方法
阿新 • • 發佈:2019-02-15
最近在寫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); } //寫到txt public 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 block e.printStackTrace(); } System.out.println("上傳圖片成功!" + newFilePath+newFileName); return newFileName; }