1 packageTOOLS;2
3 importjava.io.BufferedOutputStream;4 importjava.io.File;5 importjava.io.FileOutputStream;6 importjava.io.IOException;7 importjava.io.InputStream;8 importjava.io.OutputStream;9 importjava.util.HashMap;10 importjava.util.Map;11
12 importjavax.servlet.http.HttpServletRequest;13 importjavax.servlet.http.HttpServletResponse;14 importorg.apache.commons.fileupload.FileItemIterator;15 importorg.apache.commons.fileupload.FileItemStream;16 importorg.apache.commons.fileupload.FileUploadException;17 importorg.apache.commons.fileupload.servlet.ServletFileUpload;18 importorg.apache.commons.fileupload.util.Streams;19
20 public classHTTPPostAcceptPhoto {21
22 Map result = new HashMap();23
24 public Mapanalyze(HttpServletRequest request,25 HttpServletResponse response,String imageurl) {26 if (ServletFileUpload.isMultipartContent(request)) {//判断是否含有文件
27 insertPIC(request,imageurl);28 } else{29 txthandle(request, response);30 }31 returnresult;32 }33 //写出图片
34 private voidinsertPIC(HttpServletRequest request,String url) {35
36 ServletFileUpload upload = newServletFileUpload();37 FileItemIterator iter;38 try{39 iter =upload.getItemIterator(request);40 while(iter.hasNext()) {41 FileItemStream item =iter.next();42 String name = item.getFieldName();//filename
43 InputStream stream =item.openStream();44 System.out.println("文本" +item.isFormField());45 if (item.isFormField()) {//如果是文本
46 txt(result,name, Streams.asString(stream,"utf-8"));47 } else{48 String dir =request.getSession().getServletContext()49 .getRealPath(url);50 OutputStream fileos = null;51 byte[] buff = new byte[1];52 File image =newFile(dir, item.getName());53 System.out.println(" item.getName():"+item.getName());54 fileos = new BufferedOutputStream(newFileOutputStream(55 image));56
57 while ((stream.read(buff)) != -1) {58 fileos.write(buff);59 }60 fileos.flush();61 fileos.close();62 result.put("imagename", item.getName());//返回图片名字
63 }64 }65 } catch(FileUploadException e) {66 //TODO Auto-generated catch block
67 System.out.println(e);68 } catch(IOException e) {69 //TODO Auto-generated catch block
70 System.out.println(e);71 }72 }73 //有文本时的操作
74 private void txt(Mapresult,String name, String asString){75 result.put(name, asString);76 }77 //纯文本操作
78 public voidtxthandle(HttpServletRequest request,79 HttpServletResponse response){80 result =request.getParameterMap();81 }82
83 }