import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FormDataController {
@PostMapping(value = "/formdata", consumes = "multipart/form-data")
public String handleFormData(
@RequestPart("file") MultipartFile file,
@RequestPart("data") MultiValueMap<String, String> formData) {
// 处理文件和表单数据
return "Received file and form data";
}
@PostMapping("/x-www-form-urlencoded")
public String handleUrlEncodedData(@RequestBody MultiValueMap<String, String> formData) {
// 处理application/x-www-form-urlencoded数据
return "Received x-www-form-urlencoded data";
}
}
这段代码演示了如何在Spring Boot应用程序中处理multipart/form-data和application/x-www-form-urlencoded类型的数据。第一个方法使用@RequestPart
注解接收文件和表单数据,第二个方法使用@RequestBody
和MultiValueMap
来接收键值对。这些方法可以处理传入的数据,并返回一个响应字符串。