You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 
SOP/doc/docs/files/10104_文件上传.md

2.8 KiB

文件上传

请求接口时带上文件

客户端调用

DemoFileUploadRequest request = new DemoFileUploadRequest();

DemoFileUploadModel model = new DemoFileUploadModel();
model.setRemark("上传文件参数");
request.setBizModel(model);

List<UploadFile> files = new ArrayList<>();
String root = System.getProperty("user.dir");
System.out.println(root);
// 这里演示将resources下的两个文件上传到服务器
files.add(new UploadFile("file1", new File(root + "/src/main/resources/file1.txt")));
files.add(new UploadFile("file2", new File(root + "/src/main/resources/file2.txt")));
request.setFiles(files);

DemoFileUploadResponse response = client.execute(request);

System.out.println("--------------------");
if (response.isSuccess()) {
    List<DemoFileUploadResponse.FileMeta> responseFiles = response.getFiles();
    System.out.println("您上传的文件信息:");
    responseFiles.stream().forEach(file->{
        System.out.println(file);
    });
} else {
    System.out.println("errorCode:" + response.getCode() + ",errorMsg:" + response.getMsg());
}
System.out.println("--------------------");

客户端使用UploadFile添加上传文件

/**
 * @param name 表单名称,不能重复
 * @param file 文件
 * @throws IOException
 */
public UploadFile(String name, File file) throws IOException {
    this(name, file.getName(), FileUtil.toBytes(file));
}

其中name表示字段名称,相当于<input type="file" name="file1"/>中的name

源码详见sop-sdk

服务端接收文件

  • 方式1
/**
 * 方式1:将文件写在参数中,可直接获取。好处是可以校验是否上传
 * @param param
 * @return
 */
@ApiMapping(value = "demo.file.upload")
public FileUploadVO file1(FileUploadParam param) {
    System.out.println(param.getRemark());
    // 获取上传的文件
    MultipartFile file1 = param.getFile1();
    MultipartFile file2 = param.getFile2();
    ...
    return vo;
}

@Data
public class FileUploadParam {
    private String remark;

    // 上传文件,字段名称对应表单中的name属性值
    @NotNull(message = "文件1不能为空")
    private MultipartFile file1;

    @NotNull(message = "文件2不能为空")
    private MultipartFile file2;
}

方式1的好处是可以使用JSR-303校验文件是否上传

  • 方式2
/**
 * 方式2:从request中获取上传文件
 *
 * @param param
 * @return
 */
@ApiMapping(value = "demo.file.upload2")
public FileUploadVO file2(FileUploadParam2 param, HttpServletRequest request) {
    System.out.println(param.getRemark());
    FileUploadVO vo = new FileUploadVO();
    // 获取上传的文件
    Collection<MultipartFile> uploadFiles = UploadUtil.getUploadFiles(request);
    ...
    return vo;
}

微服务端源码参考FileUploadDemoController.java