在asp core 2.1中上传后无法访问图像

时间:2018-08-18 09:52:31

标签: c# asp.net asp.net-mvc asp.net-core

上传后,我无法访问照片进行查看。
这是上载代码 `

public async Task<string> Upload_Image(FormFile file,string name)
        {
            var newFileName = string.Empty;
            if (file.Length > 0)
            {
                var fileName = string.Empty;
                string PathDB = string.Empty;

                //Getting FileName
                fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

                //Assigning Unique Filename (Guid)
                var myUniqueFileName = Convert.ToString(Guid.NewGuid());

                //Getting file Extension
                var FileExtension = Path.GetExtension(fileName);

                // concating  FileName + FileExtension
                newFileName = myUniqueFileName + FileExtension;
                if (string.IsNullOrWhiteSpace(_env.WebRootPath))
                {
                    _env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), name);
                }
                // Combines two strings into a path.
                fileName = _env.WebRootPath + '\\' + newFileName;

                // if you want to store path of folder in database
                PathDB = name+"/" + newFileName;
                newFileName = PathDB;
                using (FileStream fs = System.IO.File.Create(fileName))
                {
                    await file.CopyToAsync(fs);
                    fs.Flush();
                }
            }

            return newFileName;

        }`

我正在使用ID作为参数'name'的参数。
当我尝试使用“ /ID/whatEverhere.jpg”访问照片时 返回NOTFOUND ??????

1 个答案:

答案 0 :(得分:0)

您将文件存储在:

 fileName = _env.WebRootPath + '\\' + newFileName;`  
 ...
 using (FileStream fs = System.IO.File.Create(fileName))

然后您返回:

PathDB = name+"/" + newFileName;
newFileName = PathDB;
...
return newFileName;

所以,这不是同一路径,在存储文件的路径中没有您的ID!
我怀疑您应该清理您的代码。