简体   繁体   English

更改上传图片的名称

[英]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. 我设法创建一个唯一的文件名,你没有将.jpg附加到图像的末尾。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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