我實(shí)現(xiàn)了一個(gè)文件上傳,其中文件與一些數(shù)據(jù)一起傳遞到后端。文件和數(shù)據(jù)必須編碼為表單數(shù)據(jù)。我以?xún)煞N方式實(shí)現(xiàn)了上傳:表單數(shù)據(jù)將文件作為二進(jìn)制字符串進(jìn)行合并表單數(shù)據(jù)將文件作為普通字符串包含(鏈接到文件)第一個(gè)選項(xiàng)適用于我,文件已成功上傳,而在第二種情況下,將顯示一條錯(cuò)誤消息:“提交的數(shù)據(jù)不是文件。請(qǐng)檢查表單上的編碼類(lèi)型。1.文件上傳,音頻文件作為二進(jìn)制字符串(工作)Form Dataaudio: (binary)title: Some Titlecontent: Some content1. 創(chuàng)建將音頻文件為二進(jìn)制的表單數(shù)據(jù)的函數(shù)和表單 ( 工作 )export class CreateStory extends Component { state = { title: "", content:"", audio:"" }; static propTypes = { addStory: PropTypes.func.isRequired };// Use Ref to clear uncontrolled file field constructor(props) { super(props); this.inputRef = React.createRef(); } onChange = (e) => { if(e.target.name === 'audio') { this.setState({ [e.target.name]: e.target.files[0] }, () => console.log(this.state.audio)) } else { this.setState({ [e.target.name]: e.target.value }, () => console.log(this.state)) } }onSubmit = e => { e.preventDefault(); let { title, content, audio} = this.state; let formDataStory = new FormData(); // create form formData formDataStory.append('audio', audio); // add audio to formData formDataStory.append('title', title); // add title to formData formDataStory.append('content', content); // add content to formData console.log (this.formDataStory); this.props.addStory(formDataStory) // call addStory function with formDataStory as Input to create new Story .then(() => { this.setState({ title: "", // clear title field after submission content:"", // clear content field after submission }); this.inputRef.current.value = ''; // clear file field after submission }) };
如何在react中轉(zhuǎn)換二進(jìn)制數(shù)據(jù)中的文件數(shù)據(jù)?
溫溫醬
2022-08-04 10:10:12