亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

spring boot項目同時傳遞參數(shù)和文件的多種方式代碼演示

 更新時間:2023年06月27日 11:28:32   作者:kangaroo.  
這篇文章主要介紹了spring boot項目同時傳遞參數(shù)和文件的多種方式,在開發(fā)接口中,遇到了需要同時接收參數(shù)和文件的情況,可以有多種方式實(shí)現(xiàn)文件+參數(shù)的接收,這里基于spring boot 3 + vue 3 + axios,做一個簡單的代碼演示,需要的朋友可以參考下

在開發(fā)接口中,遇到了需要同時接收參數(shù)和文件的情況,可以有多種方式實(shí)現(xiàn)文件+參數(shù)的接收,這里基于spring boot 3 + vue 3 + axios,做一個簡單的代碼演示。

1 簡單參數(shù) + 文件參數(shù)

參數(shù)較少時,比較方便,直接參數(shù)接受即可

1.1 后端接口

@RestController
@RequestMapping("/param")
@Validated
public class FileParamController extends BaseController {
    /**
     * 簡單參數(shù)
     *
     * @param test1
     * @param test2
     * @param file
     * @return
     */
    @PostMapping("/file-simple-param")
    public Map<String, Object> fileAndSimpleParam(@RequestParam @NotBlank String test1,
                                                  @RequestParam @NotBlank String test2,
                                                  @RequestParam MultipartFile file) {
        Map<String, Object> objectMap = new HashMap<>();
        objectMap.put("test1", test1);
        objectMap.put("test2", test2);
        objectMap.put("fileName", file.getOriginalFilename());
        return objectMap;
    }
}

1.2 前端請求

const fileAndSimpleParamFuc = (methodParam: { file: string | Blob }) => {
	let formData = new FormData()
	formData.append('test1', 'test1')
	formData.append('test2', 'test2')
	formData.append('file', methodParam.file)
	fileAndSimpleParam(formData).then(resp => {
		console.log(resp)
	})
}

fileAndSimpleParam 為封裝的api請求方法,可查看下文的 param.ts

2 簡單參數(shù)轉(zhuǎn)JavaBean + 文件參數(shù)

將各個參數(shù)封裝到一個JavaBean中接收,同時接收文件參數(shù),此時JavaBean參數(shù)不加任何注解,不支持接收List參數(shù)

2.1 后端接口

@RestController
@RequestMapping("/param")
@Validated
public class FileParamController extends BaseController {
    /**
     * 簡單參數(shù)轉(zhuǎn)JavaBean接收,不支持如:LIst<xxx> 這樣的屬性
     *
     * @param bean
     * @param file
     * @return
     */
    @PostMapping("/file-simple-bean")
    public SimpleBean fileAndSimpleJavaBean(@Validated SimpleBean bean, @RequestParam MultipartFile file) {
        bean.setFileName(file.getOriginalFilename());
        return bean;
    }
}

SimpleBean.java

@Data
public class SimpleBean {
    @NotBlank
    private String test1;
    @NotBlank
    private String test2;
    @Null(message = "The fileName is not support to be used")
    private String fileName;
}

2.2 前端請求

const fileAndSimpleJavaBeanFuc = (methodParam: { file: string | Blob }) => {
	let formData = new FormData()
	formData.append('test1', 'test1')
	formData.append('test2', 'test2')
	formData.append('file', methodParam.file)
	fileAndSimpleJavaBean(formData).then(resp => {
		console.log(resp)
	})
}

fileAndSimpleJavaBean 為封裝的api請求方法,可查看下文的 param.ts

3 簡單參數(shù)轉(zhuǎn)String + 文件參數(shù)

在這種接收方式中,使用String來接收參數(shù),在使用工具(如fastjson)手動轉(zhuǎn)為JavaBean,支持接收List參數(shù),但是需要自行校驗參數(shù)是否滿足要求

3.1 后端接口

@RestController
@RequestMapping("/param")
@Validated
public class FileParamController extends BaseController {
    /**
     * 參數(shù)轉(zhuǎn)字符串接收,支持復(fù)雜參數(shù)屬性,如:List<xxx>
     *
     * @param bean
     * @param file
     * @return
     */
    @PostMapping("/file-and-json")
    public SimpleBean fileAndJsonJavaBean(String bean, @RequestParam MultipartFile file) {
        SimpleBean simpleBean = JSON.parseObject(bean, SimpleBean.class);
        //自定義參數(shù)校驗
        List<String> valid = ValidatorUtils.validFast(simpleBean);
        if (!valid.isEmpty()) {
            throw new FailException(String.join(",", valid));
        }
        simpleBean.setFileName(file.getOriginalFilename());
        return simpleBean;
    }
}

SimpleBean.java

@Data
public class SimpleBean {
    @NotBlank
    private String test1;
    @NotBlank
    private String test2;
    private List<ParamBO> params;
    @Null(message = "The fileName is not support to be used")
    private String fileName;
}

ValidatorUtils.java

借助spring的參數(shù)校驗做自定義調(diào)用

public class ValidatorUtils {
    private static final Validator VALIDATOR_FAST = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
    private static final Validator VALIDATOR_ALL = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();
    private ValidatorUtils(){}
    /**
     * 參數(shù)校驗,遇到第一個不合法的字段直接返回不合法字段,后續(xù)字段不再校驗
     *
     * @param object
     * @return
     * @param <T>
     */
    public static <T> List<String> validFast(T object, Class<?>... groups){
        return valid(VALIDATOR_FAST, object, groups);
    }
    /**
     * 校驗所有字段并返回不合法字段
     *
     * @param object
     * @return
     * @param <T>
     */
    public static <T> List<String> validAll(T object, Class<?>... groups){
        return valid(VALIDATOR_ALL, object, groups);
    }
    private static <T> List<String> valid(Validator validator, T object, Class<?>... groups){
        Set<ConstraintViolation<T>> errors = validator.validate(object, groups);
        return errors.stream().map(ConstraintViolation::getMessage).toList();
    }
}

3.2 前端請求

const fileAndJsonStringToJavaBeanFuc = (methodParam: { file: string | Blob }) => {
	let paramList = []
	for (let i = 0; i < 3; i++) {
		let param = { username: '參數(shù)' + i, data: '參數(shù)值' + i }
		paramList.push(param)
	}
	let data = {
		test1: 'test1',
		test2: 'test2',
		params: paramList
	}
	let formData = new FormData()
	formData.append('bean', JSON.stringify(data))
	formData.append('file', methodParam.file)
	fileAndJsonStringToJavaBean(formData).then(resp => {
		console.log(resp)
	})
}

fileAndJsonStringToJavaBean 為封裝的api請求方法,可查看下文的 param.ts

4 文件放入JavaBean接收

將文件作為JavaBean的屬性,隨參數(shù)一起接收

4.1 后端接口

@RestController
@RequestMapping("/param")
@Validated
public class FileParamController extends BaseController {
    /**
     * 文件放入JavaBean一起提交
     *
     * @param bean
     * @return
     */
    @PostMapping(value = "/file-in-bean")
    public String fileInJavaBean(@Validated FileInBeanBO bean) {
        bean.setFileName(bean.getFile().getOriginalFilename());
        return bean.getFile().getOriginalFilename();
    }
}

FileInBeanBO.java

@Data
public class SimpleBean {
    @NotBlank
    private String test1;
    @NotBlank
    private String test2;
    @Null(message = "The fileName is not support to be used")
    private String fileName;
    private MultipartFile file;
}

4.2 前端請求

此處需要特別注意,需要修改Content-Type

const fileInJavaBeanFuc = (methodParam: { file: string | Blob }) => {
	let formData = new FormData()
	formData.append('test1', 'test1')
	formData.append('test2', 'test2')
	formData.append('file', methodParam.file)
	fileInJavaBean(formData).then(resp => {
		console.log(resp)
	})
}

fileInJavaBean 為封裝的api請求方法,可查看下文的 param.ts

5 文件和參數(shù)分別接收,@RequestPart注解

使用@RequestPart注解,實(shí)現(xiàn)參數(shù)與文件分別接收,應(yīng)該來說是最優(yōu)解,優(yōu)先推薦

5.1 后端接口

@RestController
@RequestMapping("/param")
@Validated
public class FileParamController extends BaseController {
    /**
     * 參數(shù)與文件分開接收,支持復(fù)雜參數(shù)屬性,如:List<xxx>
     *
     * @param bean
     * @param file
     * @return
     */
    @PostMapping("/file-and-bean")
    public FileBeanBO fileAndJavaBean(@RequestPart @Validated FileBeanBO bean, @RequestPart MultipartFile[] file) {
        String collect = Arrays.stream(file).map(MultipartFile::getOriginalFilename).collect(Collectors.joining(","));
        bean.setFileName(collect);
        return bean;
    }
}

FileBeanBO.java

@Data
public class SimpleBean {
    @NotBlank
    private String username;
    @Valid
    @NotEmpty
    private List<ParamBO> params;
    @Null(message = "The fileName is not support to be used")
    private String fileName;
    @Data
    public class ParamBO {
        private String username;
        private Object data;
    }
}

5.2 前端請求

此處需要特別注意,需要手動指定JavaBean的類型 Content-Type

const fileAndJavaBeanFuc = (methodParam: { file: string | Blob }) => {
	let formData = new FormData()
	let paramList = []
	for (let i = 0; i < 3; i++) {
		let param = { username: '參數(shù)' + i, data: '參數(shù)值' + i }
		paramList.push(param)
	}
	let data = {
		username: '張三',
		params: paramList
	}
	formData.append('bean', new Blob([JSON.stringify(data)], { type: 'application/json' }))
	formData.append('file', methodParam.file)
	fileAndJavaBean(formData).then(resp => {
		console.log(resp)
	})
}

fileAndJavaBean 為封裝的api請求方法,可查看下文的 param.ts

6 前端封裝 param.ts

export const fileAndSimpleParam = (params: any) => {
	return axios.post('/param/file-simple-param', params)
}
export const fileAndSimpleJavaBean = (params: any) => {
	return axios.post('/param/file-simple-bean', params)
}
export const fileAndJsonStringToJavaBean = (params: any) => {
	return axios.post('/param/file-and-json', params)
}
export const fileInJavaBean = (params: any) => {
	return axios.post('/param/file-in-bean', params, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
}
export const fileAndJavaBean = (params: any) => {
	return axios.post('/param/file-and-bean', params)
}

7 后記

以上5種方式,都能實(shí)現(xiàn)參數(shù)與文件同時接受,至于使用哪一種,看具體需求,參數(shù)太多的時候,可以優(yōu)先考慮@RequestPart注解。

到此這篇關(guān)于spring boot項目同時傳遞參數(shù)和文件的多種方式的文章就介紹到這了,更多相關(guān)spring boot傳遞參數(shù)和文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論