Custom file upload component
Premise:
The Upload component of Ant Design could have been used to Upload the file, but it was necessary to transfer the file and other form information to the background, so the ready-made Upload component of Ant was abandoned and the Input component was used for transformation.
HTML part:
<Input type="file" id="upload-file" multiple accept=".xls,.xlsx" onchange={(e)=>{e.persist(); /* e.targe. files is the information of the uploaded file */}}/>Copy the code
Since only Excel documents can be uploaded, I use the Accep attribute for now. Application/VTN… Multiple means multiple files can be selected from multiple files.
Js:
export async function add({file, url}) { const finalUrl = url; const formData = new FormData(); formData.append('file', file, file.name); return fetch(finalUrl, { method: 'POST', body: FormData,}).then((response) => {return response}).catch((err) => {console.log(' error ') return {err}; }); }Copy the code
The CSS part:
If you do this directly, the style is very ugly, and the text in the button can only say “select file “, sometimes the product needs to say” import file “or something like that.
<a href="javascript:;" style={{ padding: 4,color: '#000', borderWith: 1, borderStyle: 'solid', borderColor: '#ddd', borderRadius: <Input type="file" style={{lineHeight: 1.3,position: 'absolute',left: 0, right: 0, top: 0, opacity: 0, opacity: 0, opacity: 0, opacity: 0 0}} id="uploadUid" accept=".xlsx,.xls" onChange={(e) => {e.persist(); This.setstate ({fileList: [e.targe.files [0].name]})}}/> <span>{fileList. Length > 0? 'import file'} < / span > < / a > < span > {fileList. Length = = 0? 'not select file' : 'file name'} < / span >Copy the code
After this modification, the text in the button of the file uploading component can be changed at will, and the file name will be displayed as native, and the “not selected file” message will be displayed when the file is not selected.
If anything is incorrect, please correct it. If you have a better solution, thanks for sharing!
Conclusion: The custom file upload component is actually very simple, but it will take a lot of time to explore, but in the process of exploring, I can learn more knowledge.