码迷,mamicode.com
首页 > 编程语言 > 详细

java http post上传文件

时间:2016-07-14 01:48:10      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

1.上传接口

@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();
        }
        
    }

 

java http post上传文件

标签:

原文地址:http://www.cnblogs.com/simpledev/p/5668182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!