首页 > 解决方案 > not able to add one string and file to FormData in JS

问题描述

in my case , i need to add one file and one String value to formData. File Value is appending but string value is not appending

const uploadClickHandler=()=>
      {
       
        const formData = new FormData();
       
        for(let i = 0; i< files.length; i++) {
          formData.append('file', files[i])
        }
        formData.append('name','ajith')
     
        console.log(formData);
        axios.post('http://localhost:8080/hello/',formData,{
          headers: {
            "Content-Type":"multipart/form-data"
          }
        })
      

In server Side, only file is coming, not string value.

@PostMapping(value="/hello", produces = MediaType.APPLICATION_JSON_VALUE)
public ArrayList<LoadDirectoryResponse> getFile(@RequestPart(value="file") MultipartFile[] files)
{
    System.out.println(files.length);
    ArrayList<LoadDirectoryResponse> dirlist = new ArrayList<LoadDirectoryResponse>();
    
    for(int i=0;i<files.length;i++)
    {
        LoadDirectoryResponse obj = new LoadDirectoryResponse(files[i].getOriginalFilename());
        dirlist.add(obj);
    }
    return dirlist;

it printing length as 1

标签: javascriptreactjsspring-boot

解决方案


I think you need to pass that string value with body

const uploadClickHandler=()=>
  {
   
    const formData = new FormData();
   
    for(let i = 0; i< files.length; i++) {
      formData.append('file', files[i])
    }
    formData.append('name','ajith')
 
    console.log(formData);
    axios.post('http://localhost:8080/hello/',formData,{
      headers: {
        "Content-Type":"multipart/form-data"
      },
      body:{
       name:formData.name
        }
    })

推荐阅读