拖放图像然后到数据库

时间:2018-09-23 19:34:34

标签: c# asp.net

我正在使用拖放区,如果将其保存到服务器上的文件中,效果很好,但是我想将其保存到数据库中,我无法从代码隐藏中获取图像元素

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "image/png";

    string dirFullPath = HttpContext.Current.Server.MapPath("~/MediaUploader/");
    string[] files;
    int numFiles;

    files = System.IO.Directory.GetFiles(dirFullPath);
    numFiles = files.Length;
    numFiles = numFiles + 1;

    string str_image = "";

    foreach (string s in context.Request.Files)
    {
        HttpPostedFile file = context.Request.Files[s];
        string fileName = file.FileName;
        string fileExtension = file.ContentType;

        if (!string.IsNullOrEmpty(fileName))
        {
            fileExtension = Path.GetExtension(fileName);
            str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
            string pathToSave = HttpContext.Current.Server.MapPath("~/MediaUploader/") + str_image;
            file.SaveAs(pathToSave);
        }
    }

    context.Response.Write(str_image);
}

1 个答案:

答案 0 :(得分:0)

您可以通过调用file.InputStream.Read从byte.InputStream中获取组成文件的字节,并将其读入字节数组。一旦有了字节,就可以将它们写入二进制类型的数据库列。

我喜欢使用base64字符串而不是二进制字符串,因为对于各种I / O功能,它们更易于处理。因此,下面的示例假定您正在使用该方法。这绝不是生产代码,而只是一个包含必要功能的示例。

    public class DatabaseFile
    {

        /// <summary>
        /// The file name, the database column to which it corresponds is a nvarchar(256)
        /// </summary>
        public string Name = string.Empty;

        /// <summary>
        /// The Mime type of the file, the database column to which it corresponds is a nvarchar(64)
        /// </summary>
        public string Mime = string.Empty;

        /// <summary>
        /// The file data as a base64 string, the database column to which it corresponds is a ntext
        /// </summary>
        public string Data = string.Empty;

        /// <summary>
        /// The file data as a byte array
        /// </summary>
        public byte[] BinaryData
        {
            get { return Convert.FromBase64String(Data); }
            set { Data = Convert.ToBase64String(value); }
        }

        /// <summary>
        /// Constructor to create a DatabaseFile from a HttpPostedFile
        /// </summary>
        /// <param name="file"></param>
        public DatabaseFile(HttpPostedFile file)
        {
            Name = file.FileName;
            Mime = file.ContentType;
            byte[] fileBytes = new byte[file.ContentLength];
            file.InputStream.Read(fileBytes, 0, file.ContentLength);
            BinaryData = fileBytes;
        }

        /// <summary>
        /// Save the file information and data to a database table called [FileTable].
        /// </summary>
        /// <param name="sqlConnection"></param>
        public void SaveToDatabase(SqlConnection sqlConnection)
        {

            // Parameterized Insert command
            SqlCommand sqlCommand = new SqlCommand("insert [FileTable] ([Name], [Mime], [Data]) values (@Name, @Mime, @Data)", sqlConnection);

            // Create the necessary parameters
            sqlCommand.Parameters.Add("@Name", SqlDbType.NVarChar, 256);
            sqlCommand.Parameters.Add("@Mime", SqlDbType.NVarChar, 64);
            sqlCommand.Parameters.Add("@Data", SqlDbType.NText);

            // Assign the parameters
            sqlCommand.Parameters["@Name"].Value = Name;
            sqlCommand.Parameters["@Mime"].Value = Mime;
            sqlCommand.Parameters["@Data"].Value = Data;

            // Execute the command
            try
            {
                sqlConnection.Open();
                sqlCommand.ExecuteNonQuery();
            }
            finally
            {
                sqlConnection.Close();
            }

        }
    }

现在在foreach文件循环中的代码中,您将具有以下内容:

DatabaseFile dbFile = new DatabaseFile(context.Request.Files[s]);
dbFile.SaveToDatabase(sqlConnection);