如上採用asihttprequest類中的post方式上傳就行。大體思路是:上傳編碼過的字符串類型,而後在服務器端把字符串轉換成二進制流文件,接着二進制流轉換成圖片。服務器
關鍵點是myUpload.upload類型是nsdata,而nslog打印一下發現編碼過的字符串兩端還包含「<」和「>」,因此服務器端接受到的數據須要把他們刪掉,而後將其轉換爲二進制,進而轉換爲圖片。而二進制轉換成圖片的類型隨意,測試結果png和jpg均可以。eclipse
request中的forkey是本身設的關鍵字。要點就這麼多了。iphone
關於服務器端的說明見下,感謝YM幫忙測試和寫服務器端文檔,留之後用。post
String pictureFileName; //上傳圖片名測試
String pictureContentType; //上傳圖片類型ui
String pictureContent; //上傳圖片的字符串形式編碼
public static byte[] hex2byte(String str) { // 字符串轉二進制spa if (str == null)code return null;server str = str.trim(); str = str.replace(" ", ""); int len = str.length(); if (len == 0 || len % 2 == 1) return null;
byte[] b = new byte[len / 2]; try { for (int i = 0; i < str.length(); i += 2) { b[i / 2] = (byte) Integer .decode("0x" + str.substring(i, i + 2)).intValue(); } return b; } catch (Exception e) { return null; } } |
public static File fileBuild(String pictureContent){ File file = new File(F_NAME); //存放二進制內容的指定文件
//去除先後兩個尖括號 pictureContent = pictureContent.substring(1, pictureContent.length()-1);
try{ if(!file.exists()){ file.createNewFile(); } // 將字符串轉換成二進制,用於顯示圖片 int nRead = 0; byte[] imgByte = StrToByte.hex2byte(pictureContent); byte[] b = new byte[1024];
InputStream in = new ByteArrayInputStream( imgByte );
FileOutputStream output = new FileOutputStream(F_NAME, false);
while( ( nRead = in.read(b) ) != -1 ){ output.write( b, 0, nRead ); } output.flush(); output.close(); in.close();
}catch(Exception e){ e.printStackTrace(); } return file; } |
private static final int BUFFER_SIZE=16*1024; private static final String F_NAME = "D:\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp1\\work\\Catalina\\localhost\\jy\\upload_7d68c7b2_13633574de8__8000_00000000.tmp"; //封裝文件對象 private static void copy(File src,File dst){ InputStream in=null; OutputStream out=null; try { in=new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE); out=new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE); byte[] buffer=new byte[BUFFER_SIZE]; int len=0; while((len=in.read(buffer))>0){ out.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally{ if(null!=in){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if(null!=out){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } }
}
public static String fileexecute(int id,File picture,String savepath,String filename)throws Exception{ String dstPath=ServletActionContext.getServletContext().getRealPath(savepath)+"\\"+id; File mdFile=new File(dstPath); mdFile.mkdir(); File dstFile=new File(dstPath+"\\"+filename); copy(picture,dstFile); return savepath.substring(1)+"/"+id+"/"+filename; } |