简体   繁体   中英

changing name of uploaded images

What I am trying to achieve is changing the name of uploaded images to a somewhat unique string.

I have created an image gallery which is populated dynamically by database. The gallery is working fine except, that files stored in the database will be problematic if an image with the same name is uploaded!

Code in the controller for file upload:

string AdvertImage = picture1.FileName;
                    advert.AdvertImage = AdvertImage;
                    var image1Path = Path.Combine(Server.MapPath("~/Content/Images"), AdvertImage);
                    picture1.SaveAs(image1Path);

The code below is what I am working on

                    string BackImage = DateTime.Now.ToString("yyyyMMddhhmmssfffffff");
                    caradvert.BackImage = BackImage;
                    var image3Path = Path.Combine(Server.MapPath("~/Content/CarImages"), BackImage);
                    picture3.SaveAs(image3Path);

I have managed to create a unique file name thou it is not appending .jpg to the end of the image.

Any help or advice on the subject welcome

Try this:

        //save file in folder
    if (FileUpload1.PostedFile.ContentType.ToLower().StartsWith
            ("image") && FileUpload1.HasFile)
    {
        string savelocation = Server.MapPath("savedImages/");
        string fileExtention = System.IO.Path.GetExtension(FileUpload1.FileName);
        //creating filename to avoid file name conflicts.
        string fileName = Guid.NewGuid().ToString();
        //saving file in savedImage folder.
        string savePath = savelocation + fileName + fileExtention;
        FileUpload1.SaveAs(savePath);
    }

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