一、前言
通过WebFlex的org.springframework.http.codec.multipart.FilePart进行文件上传后,需要转换到SpringMvc框架的org.springframework.web.multipart.MultipartFile文件上传接口中。-解决方法当接受到FilePart后转为File,再将File转为MultipartFile对象文件,如MockMultipartFile时直接报错"MissingServletRequestPartException: Required request part 'templateFile' is not present"。
二、解决方法
将MockMultipartFile方式改为CommonsMultipartFile,具体代码如下,完整项目代码参见相关资源下载页面
package com.xwood.cloud.upload.client;@b@@b@import org.apache.commons.fileupload.FileItem;@b@import org.apache.commons.fileupload.FileItemFactory;@b@import org.apache.commons.fileupload.disk.DiskFileItemFactory;@b@import org.junit.Test;@b@import org.junit.runner.RunWith;@b@import org.springframework.beans.factory.annotation.Autowired;@b@import org.springframework.boot.test.context.SpringBootTest;@b@import org.springframework.test.context.junit4.SpringRunner;@b@import org.springframework.web.multipart.MultipartFile;@b@import org.springframework.web.multipart.commons.CommonsMultipartFile;@b@@b@import java.io.File;@b@import java.io.FileInputStream;@b@import java.io.IOException;@b@import java.io.OutputStream;@b@@b@@RunWith(SpringRunner.class)@b@@SpringBootTest@b@public class ConsumerApiTest {@b@@b@ @Autowired@b@ private ConsumerApi consumerApi;@b@@b@ private FileItem createFileItem(File file, String fieldName) {@b@ FileItemFactory factory =new DiskFileItemFactory(16,null);@b@ FileItem item = factory.createItem(fieldName,"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",true, file.getName());@b@ int bytesRead =0;@b@ byte[] buffer =new byte[8192];@b@ try {@b@ FileInputStream fis =new FileInputStream(file);@b@ OutputStream os = item.getOutputStream();@b@ while ((bytesRead = fis.read(buffer,0,8192)) != -1) {@b@ os.write(buffer,0, bytesRead);@b@ }@b@ os.close();@b@ fis.close();@b@ }catch (IOException e) {@b@ e.printStackTrace();@b@ }@b@ return item;@b@ }@b@@b@// MultipartFile mfile =new CommonsMultipartFile(fileItem);@b@ private MultipartFile createMultPartFile(File file, String fieldName){@b@ FileItem fileitem=createFileItem(file,fieldName);@b@ return new CommonsMultipartFile(fileitem);@b@ }@b@@b@ @Test@b@ public void contextLoads() throws Exception {@b@ System.out.println("111");@b@ File excelFile=new File("C:\\xwood_net\\udisk\\731\\123.xlsx");@b@ FileInputStream fileInputStream = new FileInputStream(excelFile);@b@@b@// MultipartFile multipartFile = new MockMultipartFile(excelFile.getName(), excelFile.getName(),@b@// "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileInputStream);@b@ MultipartFile multipartFile =createMultPartFile(excelFile,"file");@b@// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet@b@// application/octet-stream@b@ System.out.println("222@"+multipartFile.getSize());@b@@b@ System.out.println("333@"+consumerApi.test("123","123"));@b@@b@ String outlog= consumerApi.upload(multipartFile,"123");@b@ System.out.println("444@"+outlog);@b@ }@b@@b@}
另外,FilePart转File参考代码如下