本文转载至 http://blog.sina.com.cn/s/blog_4c70701801012inq.html
上传图片说明
1. 关键字说明
String pictureFileName; //上传图片名
String pictureContentType; //上传图片类型
String pictureContent; //上传图片的字符串形式
2. 上传流程
3. 代码
3.1 图片内容从字符串形式转换成二进制形式
public static byte[] hex2byte(String str) { // 字符串转二进制 if (str == null) return null; 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; } } |
3.2 将二进制流写入文件中
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; } |
3.3 将二进制流转换成图片并存放在相应位置
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; } |