Click here to Skip to main content
15,921,351 members

Comments by Member 13667386 (Top 4 by date)

Member 13667386 4-Mar-18 2:40am View    
MY controller looks like below:
namespace HRMS.Controllers
{
public class FileController : Controller
{
// GET: File
public ActionResult Index()
{
return View(GetFiles());
}

[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
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 (@Name, @ContentType, @Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Name", Path.GetFileName(postedFile.FileName));
cmd.Parameters.AddWithValue("@ContentType", postedFile.ContentType);
cmd.Parameters.AddWithValue("@Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}

return View(GetFiles());
}

[HttpPost]
public FileResult DownloadFile(int? fileId)
{
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id";
cmd.Parameters.AddWithValue("@Id", fileId);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}

return File(bytes, contentType, fileName);
}

private static List<filemodel> GetFiles()
{
List<filemodel> files = new List<filemodel>();
string constr = ConfigurationManager.ConnectionStrings["Constring"]!=null?ConfigurationManager.ConnectionStrings["Constring"].ConnectionString:null;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM tblFiles"))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
files.Add(new FileModel
{
Id = Convert.ToInt32(sdr["Id"]),
Name = sdr["Name"].ToString()
});
}
}
con.Close();
}
}
return files;
}
}
}
Member 13667386 1-Mar-18 7:48am View    
how i can fix?
Member 13667386 1-Mar-18 7:44am View    
please help me, im new to c#
Member 13667386 1-Mar-18 7:28am View    
thanks! it works