这篇文章主要为大家展示了java map如何转Multipart/form-data类型,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。
我就废话不多说了,大家还是直接看代码吧!
public static String mapToTxt(MapfieldMap, Map fileMap,String fileName) throws Exception{ Random random = new Random(); int j; String getLine = "\r\n"; String fileType = "Content-Type: application/octet-stream"; String doubleBar = "--"; biaoshi = "----WebKitFormBoundary"; StringBuffer sb = new StringBuffer(); for(int i = 0; i < 16;i++){ j = random.nextInt(MULTIPART_CHARS.length-2)+2; sb.append(MULTIPART_CHARS[j]); } biaoshi = biaoshi + sb.toString(); StringBuffer stringBuffer = new StringBuffer(); for (Map.Entry entity:fieldMap.entrySet()) { String name = "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()) { String name = "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); File f = entity.getValue(); FileInputStream fileInputStream = new FileInputStream(f); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte by[] = new byte[1024]; int k = 0; while ((k=fileInputStream.read(by))!=-1){ byteArrayOutputStream.write(by,0,k); } by = byteArrayOutputStream.toByteArray(); for(int i = 0; i < by.length; i++){ stringBuffer.append(by[i]); } stringBuffer.append(getLine); } stringBuffer.append(doubleBar+biaoshi+doubleBar); return stringBuffer.toString(); }
另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。