Custom picture upload components, mainly follow the MDN official document implementation. The onChange event is not triggered when the same file is uploaded a second time. React environment + Upload a single image
Finding problems:
The event is normally triggered when different images are uploaded, but not when images have just been uploaded.
Analysis problem:
The onChange event is triggered when the value changes. Therefore, you need to clear the value after each operation.
Solve a problem:
fileRef.current.value = ""; Document.getelementbyid ("image_uploads").value = "";Copy the code
PS: online similar native implementation solution replaceWith👎
document.getElementById("image_uploads").replaceWith(<input type="file" />)
Copy the code
The principle is essentially to replace the original DOM component with a new one, not necessarily.
1. There are alternatives
2. React
Complete implementation code:
The HTML code
<div className="image_upload_container"> <label id="upload_button" htmlFor="image_uploads"> <i className="iconfont Icon - a - danchuang - shangchuantupian "> < / I > < span > upload < / span > < input ref = {fileRef} onChange = {uploadFile} the accept = {fileType | | ".jpg, .gif, .png"} type="file" id="image_uploads" /> </label> <div className="preview" ref={previewRef}> </div> </div>Copy the code
Corresponding methods:
const uploadFile = (e) => { removeAllPreview(); // Draw mask + delete; const mask = document.createElement("div"); mask.className = "mask"; const icon = document.createElement("i"); icon.className = "iconfont icon-biaoge-shanchu"; icon.addEventListener("click", () => { e.stopPropagation(); removeAllPreview(); if (fileRef.current) { fileRef.current.value = ""; }}); mask.appendChild(icon); // // draw pictures; const curFile = fileRef.current && fileRef.current.files; const image = document.createElement("img"); image.src = URL.createObjectURL(curFile[0]); previewRef.current.appendChild(image); previewRef.current.appendChild(mask); If (curFile [0] && curFile [0]. Size > maxSize) {sizeRef. Current. InnerHTML = "image size no more than" + (maxSize/(1024 * 1024)). ToFixed (3) + "M"; } // Pass the file value to the external handleFile(curFile[0]); };Copy the code