this과 같은 것이 필요하다고 생각합니다.
기사는 테이블 구조 (SQL 서버) 바이너리 파일의 모든 종류의 저장 보여줍니다 업로드 페이지에서
CREATE TABLE [dbo].[Files](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[ContentType] [varchar](50) NOT NULL,
[Size] [bigint] NOT NULL,
[Data] [varbinary](max) NOT NULL,
CONSTRAINT [PK_Files] 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]
을 넣어 다음 컨트롤 : 코드에
<input type="file" name="fileInput" />
<asp:Button ID="btnUpload" Text="Upload File" runat="server" onclick="btnUpload_Click" />
이동 -behind 파일 업로드 페이지에서 다음 코드를 추가하여 버튼의 클릭 이벤트를 처리하고 파일을 데이터베이스에 저장하십시오.
protected void btnUpload_Click(object sender, EventArgs e)
{
HttpFileCollection files = Request.Files;
foreach (string fileTagName in files)
{
HttpPostedFile file = Request.Files[fileTagName];
if (file.ContentLength > 0)
{
int size = file.ContentLength;
string name = file.FileName;
int position = name.LastIndexOf("\\");
name = name.Substring(position + 1);
string contentType = file.ContentType;
byte[] fileData = new byte[size];
file.InputStream.Read(fileData, 0, size);
FileUtilities.SaveFile(name, contentType, size, fileData);
}
}
DataTable fileList = FileUtilities.GetFileList();
gvFiles.DataSource = fileList;
gvFiles.DataBind();
}
FileUtilities
클래스는 파일을 저장하는 방법이 있어야하고 나중에 데이터베이스에서 검색 :
public static void SaveFile(string name, string contentType, int size, byte[] data)
{
using (SqlConnection connection = new SqlConnection())
{
OpenConnection(connection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandTimeout = 0;
string commandText = "INSERT INTO Files VALUES(@Name, @ContentType, ";
commandText = commandText + "@Size, @Data)";
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 100);
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar, 50);
cmd.Parameters.Add("@size", SqlDbType.Int);
cmd.Parameters.Add("@Data", SqlDbType.VarBinary);
cmd.Parameters["@Name"].Value = name;
cmd.Parameters["@ContentType"].Value = contentType;
cmd.Parameters["@size"].Value = size;
cmd.Parameters["@Data"].Value = data;
cmd.ExecuteNonQuery();
connection.Close();
}
}
public static DataTable GetFileList()
{
DataTable fileList = new DataTable();
using (SqlConnection connection = new SqlConnection())
{
OpenConnection(connection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandTimeout = 0;
cmd.CommandText = "SELECT ID, Name, ContentType, Size FROM Files";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(fileList);
connection.Close();
}
return fileList;
}
public static DataTable GetAFile(int id)
{
DataTable file = new DataTable();
using (SqlConnection connection = new SqlConnection())
{
OpenConnection(connection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandTimeout = 0;
cmd.CommandText = "SELECT ID, Name, ContentType, Size, Data FROM Files "
+ "WHERE [email protected]";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
cmd.Parameters.Add("@ID", SqlDbType.Int);
cmd.Parameters["@ID"].Value = id;
adapter.SelectCommand = cmd;
adapter.Fill(file);
connection.Close();
}
return file;
}
하면 페이지 다운로드에 사용할 수있는 파일이 GridView
를 추가 나열하려면 :
<asp:GridView ID="gvFiles" CssClass="GridViewStyle"
AutoGenerateColumns="true" runat="server">
<FooterStyle CssClass="GridViewFooterStyle" />
<RowStyle CssClass="GridViewRowStyle" />
<SelectedRowStyle CssClass="GridViewSelectedRowStyle" />
<PagerStyle CssClass="GridViewPagerStyle" />
<AlternatingRowStyle CssClass="GridViewAlternatingRowStyle" />
<HeaderStyle CssClass="GridViewHeaderStyle" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server"
NavigateUrl='<%# Eval("ID", "GetFile.aspx?ID={0}") %>'
Text="Download"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
및로드 코드 숨김 다음 추가하여 다음 GetFile
페이지에서 마지막으로
protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack)
{
DataTable fileList = FileUtilities.GetFileList();
gvFiles.DataSource = fileList;
gvFiles.DataBind();
}
}
을 공동으로 다음을 추가 다운로드 기능을 구현하기위한 비공개 파일 :
protected void Page_Load(object sender, EventArgs e)
{
int id = Convert.ToInt16(Request.QueryString["ID"]);
DataTable file = FileUtilities.GetAFile(id);
DataRow row = file.Rows[0];
string name = (string)row["Name"];
string contentType = (string)row["ContentType"];
Byte[] data = (Byte[])row["Data"];
// Send the file to the browser
Response.AddHeader("Content-type", contentType);
Response.AddHeader("Content-Disposition", "attachment; filename=" + name);
Response.BinaryWrite(data);
Response.Flush();
Response.End();
}
데이터베이스에 바이너리 파일 데이터를 삽입하는 것은 일반적으로 좋지 않습니다. 파일을 디렉토리에 업로드 할 수없고 URL/파일 경로에 대한 참조를 대신 데이터베이스에 저장할 수 있습니까? – Alfie
나는 [this] (http://www.codeproject.com/Articles/308552/Upload-and-Download-Files-to-SQL-Servers-in-ASP-Ne)와 같은 것을 필요로한다고 생각한다. 이 기사에서는 모든 종류의 이진 파일을 저장하는 테이블 구조를 보여줍니다. Default.aspx 페이지는 파일을 업로드하고 나중에 다운로드하는 방법을 보여줍니다. 브라우저 (다운로드)에 파일을 보내려면 응답 객체 (기사의 GetFile.aspx 참조) 만 사용하십시오. // 브라우저에 파일 보내기 Response.AddHeader ("Content-type", contentType); Response.AddHeader ("Content-Disposition", "attachment; filename ="+ name); Response.BinaryWrite (data); Response.Flush(); Re – daspn
@ Alfie : 네, 그렇게하려고 할 수 있습니다. 그러나 나는 어떻게하는지 모른다. ASP.Net에 비교적 익숙하지 않으며 데이터베이스 하나만 알고 있습니다. 폴더에 업로드하고 거기에서 다운로드하는 경우에도 도움이 될 것입니다.내가 데이터베이스를 사용하고자하는 이유는 사용자가 자동으로 생성되어 테이블 정보에 저장된 문서 ID에 따라 노트를 참조 할 수 있기 때문입니다. –