changing name of uploaded images

2019-06-14 01:38发布

问题:

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

回答1:

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);
    }