Мне удалось заставить мой проект MVC загружать и вставлять файл в виде двоичного файла в мою базу данных, мне просто нужно иметь возможность добавить пару полей, чтобы пользователь мог заполнять одновременно, например, описание файла, должность (это будет выпадающий список)
как я могу добавить эту функцию в то, что я уже получил.Я пытался создать модель, а затем я изо всех сил пытался заставить импорт быть бинарным, этот метод работает очень хорошо, но теперь мне просто нужно добавить несколько полей, которые пользователь должен отправить, чтобы вставить в базу данных с файлом.Мне также нужно будет добавить в некоторые выпадающие поля
Create table
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblFiles](
[id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[ContentType] [nvarchar](200) NOT NULL,
Description nvarchar(500) not null,
JobTitle nvarchar(100) not null,
[Data] [varbinary](max) NOT NULL,
CONSTRAINT [PK_tblFiles] PRIMARY KEY CLUSTERED
(
[id] 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
Контроллер
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
using DatabaseUpload.Models;
namespace DatabaseUpload.Controllers
{
public class HomeController : Controller
{
// GET: Home
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"].ConnectionString;
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;
}
}
}
index
@model IEnumerable<DatabaseUpload.Models.FileModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
table {
border: 1px solid #ccc;
border-collapse: collapse;
background-color: #fff;
}
table th {
background-color: #B8DBFD;
color: #333;
font-weight: bold;
}
table th, table td {
padding: 5px;
border: 1px solid #ccc;
}
table, table table td {
border: 0px solid #ccc;
}
</style>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="postedFile" />
<input type="submit" id="btnUpload" value="Upload" />
}
@using (Html.BeginForm("DownloadFile", "Home", FormMethod.Post))
{
<input type="hidden" id="hfFileId" name="FileId" />
<input type="submit" id="btnDownload" value="Download" style="display:none" />
}
<hr />
<table cellpadding="0" cellspacing="0">
<tr>
<th style="width:50px">File ID</th>
<th style="width:120px">File Name</th>
<th style="width:80px">Download</th>
</tr>
@if (Model.Count() > 0)
{
foreach (var file in Model)
{
<tr>
<td>@file.Id</td>
<td>@file.Name</td>
<td><a href="javascript:;" onclick="DownloadFile(@file.Id)">Download</a></td>
</tr>
}
}
else
{
<tr>
<td colspan="3"> </td>
</tr>
}
</table>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function DownloadFile(fileId) {
$("#hfFileId").val(fileId);
$("#btnDownload")[0].click();
};
</script>
</body>
</html>
модель
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DatabaseUpload.Models
{
public class FileModel
{
public int Id { get; set; }
public string Name { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
}
}
Добавить в свободное текстовое поле для описания - заполняется пользователем. Добавить в раскрывающемся списке название должности для Доктора, Консультанта
, чтобы эти данные были вставлены в базу данных вместе с двоичным файлом
Был бы признателен за помощь заранее спасибо