java http post上傳文件


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM