Project scenario:
The front end uses formData to submit the form request report 400 with file upload
Problem Description:
The front end will spell the parameters into FormData format as follows:
let formData = new FormData();
if (this.$refs.basicInfo.$refs.licenseNumberPhoto.$children[0].fileList[0]) {
formData.append("licenseNumberPhoto".this.$refs.basicInfo.$refs.licenseNumberPhoto.$children[0].fileList[0].raw);
}
for (let key in this.form) {
if (this.form.hasOwnProperty(key)) {
formData.append(key, this.form[key] || ' ')}}this.$refs.form.validate(valid= > {
addCar(formData).then((response) = > {
if (response.code === 200) {
this.msgSuccess("New success");
this.form.disabled = true;
this.changeMode(); }}}})Copy the code
The backend is received with an object and an HttpServletRequest:
@PostMapping("/update")
public AjaxResult edit(TzCar tzCar, HttpServletRequest request) {
int result;
try {
result = tzCarService.updateTzCar(tzCar, request);
} catch (Exception e) {
logger.error(e.getMessage());
return AjaxResult.error(e.getMessage());
}
return toAjax(result);
}
Copy the code
Error message on console during debugging:
[Failed to convert property value of type ‘java.lang.String’ to required type ‘java.lang.Long’ for property ‘allowedPassenger’; nested exception is java.lang.NumberFormatException: For input string: “null”]
Cause analysis:
As you can see from the console exception information, a “NULL” String value appears, followed by a cast exception. FormData appEnd (); FormData appEnd (); FormData append ();
interface FormData {
append(name: string, value: string | Blob, fileName? : string):void; . }Copy the code
Clearly can see the value of append receiving value can only be string | Blob, should be turn null automatically to the string “null”.
Solution:
The front end is also easy to handle, converting null to an empty string at append:
for (let key in this.form) {
if (this.form.hasOwnProperty(key)) {
formData.append(key, this.form[key] || ' ')}}Copy the code