2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Antd の Uploadでファイル制御&送信

Last updated at Posted at 2021-02-18

#手動でUploadするファイルの制御(自分のStateで管理したい)

##Upload文

<Upload {...props} customRequest={this.dummyRequest}>
</Upload>

###customRequestでuploadを騙す(実際あげてない)

Upload.js
    dummyRequest({ file, onSuccess }){
        setTimeout(() => {
            onSuccess("ok");
        }, 0);
    }

###Fileあげる前にとリストから削除の制御(自分はUIDで指定して削除する)

const props = {
    onRemove: file => {
        this.removeFromFileList(file.uid)
    },
    beforeUpload: file => {
        this.addToFileList(file)
        return false;
     }   
}
addToFileList = file => {
    this.setState(state => ({
        fileList: [...state.fileList, file]
    })));

removeFromFileList = uid => {
    this.setState(state => {
        const newFileList = state.fileList.filter(file => file.uid !== uid);
        return{
            fileList: newFileList
        };
    });

##SpringにファイルとJSONをアップロードしたい時

###formDataでfileを入れたい時

Form.js
const submitData = new FormData();

submitData.append("data", JSON.stringify(data));
const files = this.state.fileList;

####最初はこんな感じで試したが、なぜかcontrollerに届く時fileに何も入ってなかった
submitData.append("file",this.state.fileList)

####色々調べて、こんな風に入れたら成功しました

files.forEach(file => {
    submitData.append("file", file)
});

##Fetch文(Content-Type指定しない)

fetch(URL.SUBMIT, {
    method: "POST",
    body: submitData
})

#BackEndのControllerはこんな感じ

FormController.java

@PostMapping(value= "/submit")
public void submitForm(@RequestParam("data") String data, @RequestParam("file") List<MultipartFile> file) throws JsonProcessingException {
    ///FormDataなので、中のjsonはStringの形式です、受け取った後対応するクラスに変換すれば良い
    MyForm form = new ObjectMapper().readValue(data, MyForm.class);
    this.myService.submitForm(data, file);
}

##参考したサイト

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?