zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java http post上传文件详解编程语言

2023-06-13 09:20:44 时间
@IgnoreToken 

 @RequestMapping(value = "/upload/cpicFile", method = RequestMethod.POST) 

 public void cpicFile(HttpServletResponse response, HttpServletRequest request){ 

 ErrorCode errorCode = ErrorCode.FAILED; 

 Map String,Object reqData = this.getContent(request); 

 String path = SysConf.CPIC_WORKBASEDIR; //上传路径 

 try { 

 String name = (String)reqData.get("name"); 

 String content = (String)reqData.get("content"); 

 byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(content); 

 //写入文件 

 File fileTmp = new File(path + name); //临时文件 

 FileOutputStream fop = new FileOutputStream(fileTmp); 

 if (!fileTmp.exists()) { 

 fileTmp.createNewFile(); 

 fop.write(bytes); 

 fop.flush(); 

 fop.close(); 

 System.err.println("Done"); 

 errorCode = ErrorCode.SUCCESS; 

 } catch (Exception e){ 

 logger.error("上传CPIC图片异常",e); 

 errorCode = ErrorCode.SYS_ERROR; 

 sendResponseContent(response, reqData, errorCode); 

 }

2.测试接口

@Test 

 public void testCpicUploadFile(){ 

 try { 

 Map String,Object paramMap=new HashMap (); 

 paramMap.put("name", "cpic-160714.xml"); 

 File f = new File("C:/sftp/cpic-20160713-3.xml"); 

 InputStream in = new FileInputStream(f); 

 byte[] b = new byte[(int)f.length()]; //创建合适文件大小的数组 

 in.read(b); //读取文件中的内容到b[]数组 

 in.close(); 

 String s = new String(b); 

 System.out.println("s = " + s); 

 System.out.println("b1 = " + b); //内存地址 

 String ss = org.apache.commons.codec.binary.Base64.encodeBase64String(b); //base64编码 

 System.out.println("ss = " + ss); 

 System.out.println("b2 = " + Base64.decodeBase64(ss)); //内存地址 

 paramMap.put("content", ss); 

 //@IgnoreToken 

// paramMap.put("token", "54ungzbaach65xypcceq48gd6jwlyros"); //token可以加一个注解。 

 System.out.println("paramMap="+paramMap); 

 HttpResult httpResult = HttpUtil.post("/cpic/upload/cpicFile",paramMap); 

 System.out.println(httpResult); 

 } catch (Exception e) { 

 e.printStackTrace(); 

 }

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/15248.html

cjavaxml