簡體   English   中英

在c#中保存多個圖像

[英]Saving multiple images in c#

我正在嘗試使用此代碼保存多個圖像。 但它保存所有文件,包括視頻,縮略圖和圖像。 我需要做的只是保存圖像。 我在這做錯了什么? 謝謝

    List<string> img = new List<string>();
                HttpFileCollection httpFileCollection = Request.Files;
                for (int i = 0; i < httpFileCollection.Count; i++)
                {
                    HttpPostedFile httpPostedFile = httpFileCollection[i];
                    if (httpPostedFile.ContentLength > 0  && httpPostedFile.ContentType.StartsWith("image/"))
                    {
                        httpPostedFile.SaveAs(Server.MapPath("~/Icon/") + System.IO.Path.GetFileName(httpPostedFile.FileName));
                        img.Add(Server.MapPath("~/Icon/") + System.IO.Path.GetFileName(httpPostedFile.FileName));
                    }
                    
                }

cmd.Parameters.AddWithValue("@ImageURL", img.ToArray().Length > 0 ? String.Join(",", img.ToArray()) : Path.GetFileName(FileUpload2.PostedFile.FileName));

您的代碼從不檢查圖像的類型並保存所有文件。 您可以通過檢查ContentType字段或文件的擴展名來檢測圖像,例如。

HttpFileCollection httpFileCollection = Request.Files;
for (int i = 0; i < httpFileCollection.Count; i++)
{
    HttpPostedFile httpPostedFile = httpFileCollection[i];
    if (httpPostedFile.ContentLength > 0 
       && httpPostedFile.ContentType.StartsWith("image/"))
    {
         ...
    }
}

如果您知道圖像始終來自安全源,您也可以檢查文件擴展名

HttpFileCollection httpFileCollection = Request.Files;
for (int i = 0; i < httpFileCollection.Count; i++)
{
    HttpPostedFile httpPostedFile = httpFileCollection[i];
    string fileNameExtension = System.IO.Path.GetExtension(httpPostedFile.FileName);
    if (httpPostedFile.ContentLength > 0 &&  fileNameExtension ==".Jpg")
    {
         ...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM