0

hi i want to attach multiple file using jquery ajax and save it in a column of table whose datatype is blob.i have no idea what different property need to be taken in model class i have taken a single variable Attach of HttpPostedFileBase type model class

  public class Ipcell
  {
   public string CaseId { get; set; }
   public HttpPostedFileBase Attach { get; set; }
  }

view is a partial view where file upload button is available apart from other value and submit button is given at bottom.after attaching multiple file then click on submit button all values in that partial view along with different attachment should be saved in database,i.e attachments in a blob type column of table.

@model Smart.Models.Ipcell
<div>
<div> caseid<input id="Rcid" type="text" value="@Model.CaseId" /></div><br />
<div>attachment<input id="Rattc" type="file" style="margin-left:7%;padding-left:30%;"/></div><br />
<input id="Rsub" type="submit" />
</div>

on clicking 'RSub' data should be save to data base through controller using jquery ajax. jquery side

$(document).on("click", '#Rsub1', function (e) { 
 var casedetail42={};
 var casedetail42s=[];           
casedetail42["CaseId"] = $('#Rcid').val();
casedetail42["Attach1"] =$('#Rattc').prop('files')[0];
casedetail42s.push(casedetail42); 
 $.ajax({
          type:"POST",
          url:"/Home/RaisePReq",
          data:JSON.stringify(casedetail42s),
          contentType:"application/json; charset=utf-8",
          datatype:"json",
          success:function(r){                        
          alert(r);
         },
     });
  }); 

Controller side, in controller side i am not getting any value in stream fs

[HttpPost]
public JsonResult RaisePReq(List<Pcell> casedetail42)
 {           
   Byte[] bytes = null;
   Stream fs = casedetail42[0].Attach1.InputStream;
   BinaryReader br = new BinaryReader(fs);
   bytes = br.ReadBytes((Int32)fs.Length);
   try
    {
      conn.Open();
      string qry1_1 = "query for insert file upload value in a column with blob format"
      OracleCommand command = new OracleCommand(qry1_1, conn);
      command.Parameters.Add(":IBD_ATTACHMENTS", bytes);    
      int insertedRecords = command.ExecuteNonQuery();
      return Json(insertedRecords);
     }
  }

how to achieve it any idea would be appreciated.

7
  • 1
    You need to check this link c-sharpcorner.com/blogs/… this is the perfect example of multiple file upload with ajax + MVC Commented Sep 7, 2020 at 7:04
  • @PurveshPatel i want to store multiple file in blob datatype format. Commented Sep 7, 2020 at 7:51
  • Check this link : jqueryscript.net/other/image-to-blob.html Commented Sep 7, 2020 at 8:43
  • where are you stuck with this exactly? Have you done any research or made any attempts? Commented Sep 7, 2020 at 8:57
  • @ADyson i have no idea on clicking file upload button how multiple file will be attach and then from ajax how i will send those file to controller and controller will store it in a column of a table which is in Blob type.I need the syntax. Commented Sep 7, 2020 at 10:49

1 Answer 1

1

You have to use an array of HttpPostedFileBase in your form response model:

public class UploadModel  
{  
    public HttpPostedFileBase[] fileArr { get; set; }           
}  

Add a method like this to the controller:

[HttpPost]
        public ActionResult UploadFiles(HttpPostedFileBase[] files)
        {
            foreach (HttpPostedFileBase file in files)
            {
                if (file != null)
                    file.SaveAs(Path.Combine(Server.MapPath("~/UploadedFiles/") + Path.GetFileName(file.FileName)));
            }

            return View();
        }

Add multiple file input and upload button to the view:

<input type="file" id="FileUpload1" multiple />  
<input type="button" id="btnUpload" value="Upload Files" /> 

Use this script (Don't forget to replace'YourControllerName' with the controller name):

<script>  
$(document).ready(function(){  
    $('#btnUpload').click(function () {  
 
            var fileUpload = $("#FileUpload1").get(0);  
            var files = fileUpload.files;  
              
            var fileData = new FormData();  
  
            for (var i = 0; i < files.length; i++) {  
                fileData.append(files[i].name, files[i]);  
            }  
                    
            $.ajax({  
                url: '/YourControllerName/UploadFiles',  
                type: "POST",  
                contentType: false, 
                processData: false, 
                data: fileData,  
                success: function (result) {  
                    alert(result);  
                },  
                error: function (err) {  
                    alert(err.statusText);  
                }  
            });  

    });  
});  
</script>  

If you want to save the posted file to the database, Create a table like this, the FileData column with varbinary(max) hold the file:

CREATE TABLE [dbo].[TblFile](
    [FileId] [int] IDENTITY(1,1) NOT NULL,
    [FileName] [nvarchar](50) NULL,
    [ContentType] [nvarchar](200) NULL,
    [FileData] [varbinary](max) NULL,
 CONSTRAINT [PK_TblFile] PRIMARY KEY CLUSTERED 
(
    [FileId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Sample Code to Save Posted File in DataBase:

byte[] bytes;
        using (BinaryReader br = new BinaryReader(postedFile.InputStream))
        {
            bytes = br.ReadBytes(postedFile.ContentLength);
        }
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = "INSERT INTO tblFiles VALUES (@FileName, @ContentType, @FileData)";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(postedFile.FileName));
                cmd.Parameters.AddWithValue("@ContentType", postedFile.ContentType);
                cmd.Parameters.AddWithValue("@FileData", bytes);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
Sign up to request clarification or add additional context in comments.

7 Comments

This only partially answers the question. OP is also asking about how to structure the C# code. And also, your answer will be of far higher quality if you add some explanation of why you used this code, and what problem(s) it solves.
@ADyson I have edited my answer. I tried to improve quality by explaining Model, View and Controller layers.
@Ghanat i have edited my question and i want to save files or attachments in column of a table whose datatype is blob...
@Mohan you have to make a column with [varbinary](max) datatype, I have added a sample script for creating table and inserting code.
@Ghanat i am using oracle db , so i'm asking how to do it in case of blob datatype.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.