简体   繁体   中英

Save image as profilePicture{id}.png with react and js

I have a React project where I'm trying to save a picture in a folder in the application. I have a form on the page looking like this:

 <div className='editProfile' style={{display: "flex", flexDirection: "column", textAlign: "center"}}>
                <h1 >Change Profilepicture</h1> 
                    <form  id='form' target='invisible'>
                        <div style={{marginTop: "3%", position: "relative", width: "max-content", verticalAlign: "middle", display: "inline-block"}}>
                            <img className='profilePicture' 
                                style={{paddingBottom: "0", width: "100px", height: "100px"}}
                                id='image' src={"/profile-pictures/profilePicture" + props.id + ".png"} onError={({ currentTarget }) => {
                                currentTarget.onerror = null; 
                                currentTarget.src="/profile-pictures/profilePicture.png";
                            }} />
                        <input className='roundEditButton' type="button" value="&#128394;" onClick={(e) =>{buttonClick()}}/><br/>
                        </div><br/>
                        <input style={{display: "none"}} type="file" name="mypic" id="mypic" required accept="image/png, image/gif, image/jpeg" onChange={(e) => {onChange()}}/>
                        <input type="submit" value="Change profilepicture" style={{width: "auto"}} onClick={(e) => {changePP()}}/> 
                        <input type="button" onClick={(e) => {window.location.href = "/account/edit"}} value="Back" />
                    </form>
                    
                </div>
            </main>

(You can ignore the picture I included its only for user experience purposes)

When submitted this function is being called:

  const changePP = () => {
        const form = document.getElementById("form");
  if (form) {
    form.addEventListener("submit", (e) => {
      e.preventDefault();
      const formData = new FormData(form);
      formData.append('profileID', props.id)
      Axios
        .post(settings.config.SERVER_URL + "/uploadProfilePicture", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    });
    }
    }

It sends a post axios request to my backend server. I also append a Id which is the purpose of this question.

In the backend my code looks like this:

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, settings.ABSOLUT_PICTURE_PATH)
    },
    filename: function (req, file, cb) {
        cb(null, "profilePicture" + ".png")
        //HERE I WANT TO NAME THE PICTURE profilePicture + id + .png

    }
})

const maxSize = 2 * 1000 * 1000;

var upload = multer({ 
    storage: storage,
    limits: { fileSize: maxSize },
    fileFilter: function (req, file, cb){
        var filetypes = /jpeg|jpg|png/;
        var mimetype = filetypes.test(file.mimetype);
        var extname = filetypes.test(path.extname(file.originalname).toLowerCase());         
        if (mimetype && extname) {
            return cb(null, true);
        }
        cb("Error: File upload only supports the " + "following filetypes - " + filetypes);
    } 
}).single("mypic"); 

app.post(settings.PREFIX + "/uploadProfilePicture",function (req, res, next) {  
    id = req.body.profileID
    console.log(next)
    upload(req,res,function(err) {
        if(err) {
            res.send(err)
        } else {
            res.send("Success, Image uploaded!")
        }
    })

})

Unfortunately I dont know how I can get the profileID (like mentioned before) and put it into the name of the image. My question is basically how I can access the formData and get my profileID so I can include it in the name of the image.

I'm not familiar with the libraries you're using, but it looks like you have access to the request from multer:

filename: function (/**/ req /**/, file, cb) {

So, just pull it from there?

{
    filename: function (req, file, cb) {
        const profileId = req?.body?.profileID;
        if(profileId == null || profileId.match(/^\d+$/) == null)throw new Error('Invalid ID.');
        cb(null, `profilePicture${profileId}.png`);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM