MultipartFile后台调用文件上传接口

 测试类注入

@RunWith(SpringRunner.class)  org.junit.runner.RunWith(这个包,需引入)
@SpringBootTest(classes = UploadDownloadController.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.toone.utility", "com.toone.core.dao"})

定义SpringBoot测试类

Logger log = LoggerFactory.getLogger(JunitTestMethod.class);

private int port = 8083;

private URL base;

@Autowired
private TestRestTemplate restTemplate;

public void setUp(){
    try {
        String url = String.format("http://localhost:8083/utility/updown/fwUpload");
        this.base = new URL(url);
    }catch (Exception e){
        e.printStackTrace();
    }
}
@Test
public void  uploadFileByHTTP() throws Exception{
    String filePath="D:\\crebas.sql";
    File postFile=new File(filePath);
    // String filename=postFile.getName();
    long length=postFile.length();
    String lengths = Long.toString(length);
    Map postParam =new HashMap();
    postParam.put("fileType","泛微OA签名文件");
    postParam.put("module","档案归档-借阅");
    String postUrl="http://localhost:8083/utility/updown/fwUpload";
    Map resultMap = new HashMap();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try{
        //把一个普通参数和文件上传给下面这个地址    是一个servlet
        HttpPost httpPost = new HttpPost(postUrl);
        httpPost.addHeader("Authorization", "Token 666abbf788ef1aacdb76a4f711509a8b391b6c8d");
        //把文件转换成流对象FileBody
        FileBody fundFileBin = new FileBody(postFile);
        //设置传输参数
        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
        multipartEntity.addPart("chunk", fundFileBin);
        //设计文件以外的参数
        Set keySet = postParam.keySet();
        for (Object key : keySet) {
           multipartEntity.addPart((String) key, new StringBody((String) postParam.get(key), ContentType.create("text/plain", Consts.UTF_8)));
        }
        multipartEntity.addPart("chunk_offset", new StringBody("0", ContentType.create("text/plain", Consts.UTF_8)));
        multipartEntity.addPart("chunk_size", new StringBody(lengths, ContentType.create("text/plain", Consts.UTF_8)));

        HttpEntity reqEntity =  multipartEntity.build();
        httpPost.setEntity(reqEntity);

        log.info("发起请求的页面地址 " + httpPost.getRequestLine());
        //发起请求   并返回请求的响应
        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            log.info("----------------------------------------");
            //打印响应状态
            log.info(String.valueOf(response.getStatusLine()));
            resultMap.put("statusCode", response.getStatusLine().getStatusCode());
            //获取响应对象
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                //打印响应长度
                log.info("Response content length: " + resEntity.getContentLength());
                //打印响应内容
                resultMap.put("data", EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
            }
            //销毁
            EntityUtils.consume(resEntity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.close();
        }
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally{
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    log.info("uploadFileByHTTP result:"+resultMap);
    // return resultMap;
}

 Controlelr

@PostMapping("/fwUpload")
@ResponseBody
public Return<?> fwUpload(HttpServletRequest request, String module,String fileType) {
   //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
   CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
   //判断是否多文件上传
   if (multipartResolver.isMultipart(request)) {
      //将request变成多部分request
      MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
      Map<String, String[]> map = multiRequest.getParameterMap();
      //获取multiRequest 中所有的文件名
      Iterator<String> iter = multiRequest.getFileNames();
      //遍历所有文件
      while (iter.hasNext()) {
         MultipartFile file = multiRequest.getFile(iter.next().toString());
         //to do
         FileUpload upload = new FileUpload();
         upload.setFile(file);
         upload.setModule(module);
         upload.setFileType(fileType);
         upload.setFileType("0");
         SysFile sysFile = uds.upload(upload);
         return Return.success(sysFile);
      }
   }
   /*if (file.length() == 0) {
      return Return.failed(ResultCode.RESULT_NULL.getCode(), ResultCode.RESULT_NULL.getDepict());
   }
   SysFile sysFile = uds.fwUpload(file,module,fileType);*/
   return Return.success();
}

Service

@Override
public SysFile upload(FileUpload param) {
    UserInfo userInfo = userInfoContext.getUserInfo();
    //1、文件上传 
    MultipartFile file = param.getFile();
    String fileName = file.getOriginalFilename();
    String realFileName = fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1);
    String suffixName = UtilHelper.getSuffixName(realFileName);
    String newFileName = UtilHelper.generateNewFileName() + "." + suffixName;
    //文件路径:/files/'当前日期'/'服务模块'/'文件后缀'
    StringBuffer sb = new StringBuffer("");
    sb.append(basePath)
            .append(File.separatorChar)
            .append(UtilHelper.intradayDirectory())
            .append(File.separatorChar)
            .append(param.getModule())
            .append(File.separatorChar)
            .append(suffixName);
    File temp = new File(sb.toString() + File.separatorChar + newFileName);
    if (!temp.getParentFile().exists()) {
        temp.getParentFile().mkdirs();
    }
    try {
        file.transferTo(temp);
    } catch (IllegalStateException e) {
        e.printStackTrace();
        throw new RuntimeException("上传文件失败!");
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("上传文件失败!");
    }
    //2、存储文件信息 自定义业务内容
    SysFile sf = new SysFile();
    sf.setId(IDUtil.getUUID());
    sf.setCid(param.getCid());
    sf.setEid(userInfo.getEid());
    sf.setIp(userInfo.getClientIP());
    sf.setUserId(userInfo.getUserId());
    sf.setMasterId(param.getMasterId());
    sf.setModule(param.getModule());
    sf.setFileType(param.getFileType());
    sf.setName(realFileName);
    sf.setNewName(newFileName);
    sf.setComments(param.getComments());
    sf.setProjectId(param.getProjectId());
    sf.setProjectName(param.getProjectName());
    sf.setMenuName(param.getMenuName());
    sf.setFileStatus("0");
    sf.setPermissionOrgId(param.getPermissionOrgId());
    sf.setPermissionOrgName(param.getPermissionOrgName());
    sf.setPermissionUserId(param.getPermissionUserId());
    sf.setPermissionUserName(param.getPermissionUserName());
   // sf.setCtime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
    sf.setPath(UtilHelper.intradayDirectory()
            + "/" + param.getModule()
            + "/" + suffixName
            + "/" + newFileName);
    if (file.getSize() == 0) {
        sf.setSize("0");
    } else {
        String size_ = BigDecimal.valueOf(file.getSize()).divide(new BigDecimal(1000), 3, BigDecimal.ROUND_HALF_UP).toString();
        sf.setSize(size_);
    }
    fileDao.addPo(sf);
    return sf;
}
上一篇:【汇编语言与计算机系统结构笔记07】条件码,比较、测试、条件跳转与条件转移指令,结合微体系结构与流水的说明


下一篇:2021-06-16