MultipartFile 和@RequestBody不能同时使用

 MultipartFile 和@RequestBody不能同时使用_第1张图片

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 annexs;
}

你可能感兴趣的:(java,java)