MultipartFile 和@RequestBody不能同时使用

发布时间:2024年01月10日

?

package com.dj.springtest.controller;

import com.alibaba.fastjson.JSON;
import com.dj.springtest.model.dto.UploadDTO;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * User: ldj
 * Date: 2024/1/10
 * Time: 22:10
 * Description: No Description
 */
@RestController
public class FileController {

    @PostMapping(value = "/test/upload1", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public String upload(@RequestPart("file") MultipartFile file, UploadDTO uploadDTO) {
        System.out.println(file.getOriginalFilename());
        System.out.println(JSON.toJSONString(uploadDTO));

        return "文件上传成功";
    }

    //ModelAttribute 可以省略不写
    @PostMapping(value = "/test/upload2", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public String upload(@ModelAttribute UploadDTO uploadDTO) {
        System.out.println(uploadDTO.getUserId());
        System.out.println(uploadDTO.getFileName());
        for (MultipartFile annex : uploadDTO.getAnnexs()) {
            System.out.println(annex.getOriginalFilename());
        }

        return "多文件上传成功";
    }
}
package com.dj.springtest.model.dto;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * User: ldj
 * Date: 2024/1/10
 * Time: 22:15
 * Description: No Description
 */
@Data
@Accessors(chain = true)
public class UploadDTO {

    private String userId;

    private String fileName;

    List<MultipartFile> annexs;
}

文章来源:https://blog.csdn.net/dj1955/article/details/135515165
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。