I am able to send request with multipartfile via Postman whereas my frontend application cannot send.
My backend code:
@PostMapping(consumes = {"multipart/form-data"})
public ResponseEntity<File> uploadFile(@ModelAttribute @RequestBody FileAddRequestDto request) {
//do some stuff
}
And dto is:
@Data
public class FileAddRequestDto {
private Integer userId;
private Integer customerId;
private MultipartFile multipartFile;
}
Above backend code is working with postman but not working with the following axios code with react:
export async function addFile(userId, customerId, file) {
var bodyFormData = new FormData();
bodyFormData.append("userId", userId); //integer
bodyFormData.append("customerId", customerId); //integer
bodyFormData.append("multipartFile", file); //file
return await axios({
method: "post",
url: "http://localhost:8080/file",
data: bodyFormData,
enctype: "multipart/form-data",
headers: {
Accept: "application/json",
},
processData: false, // Important!
contentType: false,
cache: false,
})
Above function is called by the react method:
const addNewFile = async (userId, customerId, file) => {
await service.addFile(userId, customerId, file);
}
return (
<>
<input type="text" placeholder="userId" value={userId} onChange={e => setUserId(e.target.value)}></input>
<input type="text" placeholder="customerId" value={customerId} onChange={e => setCustomerId(e.target.value)}></input>
<input type="file" value={file} onChange={e => setFile(e.target.value)}></input>
<Button onClick={() => addNewFile(userId, customerId, file)} className='addButton'>Add</Button>
</>
);
}
Here is the backend response:
message: "org.springframework.validation.BeanPropertyBindingResult: 1 errorsnField error in object 'fileAddRequestDto' on field 'multipartFile': rejected value ["C:\\fakepath\\Screen Shot 2022-04-14 at 11.55.46.png"]; codes [typeMismatch.fileAddRequestDto.multipartFile,typeMismatch.multipartFile,typeMismatch.org.springframework.web.multipart.MultipartFile,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [fileAddRequestDto.multipartFile,multipartFile]; arguments []; default message [multipartFile]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile' for property 'multipartFile'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile' for property 'multipartFile': no matching editors or conversion strategy found]"
How can I send request properly from frontend ?