简体   繁体   中英

How to process uploaded files in ASP.NET core 2.0

We are trying to migrate our code from ASP.NET that was written some time ago to ASP.NET Core 2.0.

This piece of code stores a document in SQL Server and retrieves it.

***Original Code:*** 

protected void btnUpload_Click(object sender, EventArgs e)
{
    foreach (HttpPostedFile postedFile in multipleUpload.PostedFiles)
    {
        string filename = Path.GetFileName(postedFile.FileName);
        string contentType = postedFile.ContentType;
        using (Stream fs = postedFile.InputStream)
        {
            using (BinaryReader br = new BinaryReader(fs))
            {
                byte[] bytes = br.ReadBytes((Int32)fs.Length);
                string constr = ConfigurationManager.ConnectionStrings["ab"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string query = "insert into ftr_UploadMultiple (name,contentType,data) values (@Name, @ContentType, @Data)";
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@Name", filename);
                        cmd.Parameters.AddWithValue("@ContentType", contentType);
                        cmd.Parameters.AddWithValue("@Data", bytes);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();

We did try with the following code, it only stores 0 bytes in the DB: Any suggestions around this should be really helpful.

Our Code in ASP.NET Core 2.0

if (file.Length > 0)
{
    using (var stream = new
    FileStream(filePath, FileMode.Create))
    {
        await file.CopyToAsync(stream);
        using (BinaryReader br = new BinaryReader(stream))
        {
            byte[] bytes = br.ReadBytes((Int32)stream.Length);
            string constr = "<Connection String";
            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = "insert into ftr_UploadMultiple (data) values (@Data)";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Data", bytes);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();

I have deliberately removed the closing } s. Also, facing an issue in Downloading already uploaded file as Response.Binarywrite() is not available in ASP.NET Core 2.0.

After you call CopyToAsync to copy the bytes from the upload file to the filestream, the filestream's position is at the end. When you then attempt to read from the filestream, you're only reading the null byte at the end, resulting in 0 bytes being read.

The simplest solution is to just add the following before you read:

stream.Position = 0;

However, unless you actually need to write the file to the filesystem as well, this is just extraneous work. It would be better to copy the upload file's stream to a MemoryStream and then simply use ToArray to get the bytes from that: no need for additional reader.

Try get bytes array from InputStream

// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);

ASP.NET Core

if (file.Length > 0)
{
    using (BinaryReader br = new BinaryReader(file.InputStream))
    {
        /* ... use file.Length or file.ContentLength */

        byte[] bytes = br.ReadBytes(file.Length);

        /* ... File Processing (bytes) */           
    }
}

.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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