java map转Multipart/form-data类型body实例
我就废话不多说了,大家还是直接看代码吧!
publicstaticStringmapToTxt(MapfieldMap,Map fileMap,StringfileName)throwsException{ Randomrandom=newRandom(); intj; StringgetLine="\r\n"; StringfileType="Content-Type:application/octet-stream"; StringdoubleBar="--"; biaoshi="----WebKitFormBoundary"; StringBuffersb=newStringBuffer(); for(inti=0;i<16;i++){ j=random.nextInt(MULTIPART_CHARS.length-2)+2; sb.append(MULTIPART_CHARS[j]); } biaoshi=biaoshi+sb.toString(); StringBufferstringBuffer=newStringBuffer(); for(Map.Entry entity:fieldMap.entrySet()){ Stringname="Content-Disposition:form-data;name=\""+entity.getKey()+"\""; stringBuffer.append(doubleBar+biaoshi); stringBuffer.append(getLine); stringBuffer.append(name); stringBuffer.append(getLine); stringBuffer.append(getLine); stringBuffer.append(entity.getValue()); stringBuffer.append(getLine); } for(Map.Entry entity:fileMap.entrySet()){ Stringname="Content-Disposition:form-data;name=\""+fileName+"\";filename=\""+entity.getValue().getName()+"\""; stringBuffer.append(doubleBar+biaoshi); stringBuffer.append(getLine); stringBuffer.append(name); stringBuffer.append(getLine); stringBuffer.append(fileType); stringBuffer.append(getLine); stringBuffer.append(getLine); Filef=entity.getValue(); FileInputStreamfileInputStream=newFileInputStream(f); ByteArrayOutputStreambyteArrayOutputStream=newByteArrayOutputStream(); byteby[]=newbyte[1024]; intk=0; while((k=fileInputStream.read(by))!=-1){ byteArrayOutputStream.write(by,0,k); } by=byteArrayOutputStream.toByteArray(); for(inti=0;i 补充知识:java如何取出传参数格式为form-data中的值
publicMapTest(HttpServletRequestrequest,HttpServletRequestresponse)throwsException{ Map returnMap=newHashMap (); Stringa=request.getParameter("a");//取出form-data中a的值 Stringb=request.getParameter("b");//取出form-data中a的值 //取出form-data中的二进制字段 MultipartHttpServletRequestmultipartRequest=(MultipartHttpServletRequest)request; MultipartFilemultipartFile=multipartRequest.getFile("file");//file是form-data中二进制字段对应的name System.out.println(multipartFile.getSize()); Map resultMapsReturn=newHashMap<>(); StringimagePath="C:\\Users\\win\\Desktop\\1.jpg"//把取出来的二进制保存图片到本地 if(multipartFile.getSize()<=0){ resultMapsReturn.put("resultcode","0"); resultMapsReturn.put("msg",DisWebConst.ERROR_TITLE); }else{ InputStreamis=multipartFile.getInputStream(); OutputStreamout=newFileOutputStream(imagePath); IOUtils.copy(is,out); is.close(); out.close(); } 以上这篇javamap转Multipart/form-data类型body实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。