是這樣的,我今天需要一個小功能,是把檔案上傳至sqlserver裡,
我後來有找到參考網站,我是參考這個
http://www.dotnetawesome.com/2013/11/how-to-upload-and-download-files-tofrom.html
只是為什麼我打完後,用chrome開啟,無法上傳,網頁直接顯示localhost 拒絕連線。
但用edge就可以上傳,但也只能上傳一個,若上傳一個以上他就會顯示這種錯誤
以下是我的程式碼
前端:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication3._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h3>File Upload / Download from/to Database using ASP.NET</h3>
<div>
<table>
<tr>
<td>select File:</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" /></td>
<td>
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click1" /></td>
</tr>
</table>
<br />
<div>
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal">
<ItemTemplate>
<table>
<tr>
<td><%#Eval("FileName","File Name:{0}") %></td>
</tr>
<tr>
<td><%# Convert.ToDecimal(Eval("Filesize"))/1024%> KB</td>
</tr>
<tr>
<td>
<asp:LinkButton ID="lbtnDownload" runat="server" CommandName="Download" CommandArgument=<%# Eval("FileID") %>>Download</asp:LinkButton></td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</div>
</asp:Content>
後端部分:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateUploadedFiles();
}
}
private void PopulateUploadedFiles()
{
using (UpLoadDatabase1Entities uc = new UpLoadDatabase1Entities())
{
List<UploadedFile> allFiles = uc.UploadedFiles.ToList();
DataList1.DataSource = allFiles;
DataList1.DataBind();
}
}
protected void btnUpload_Click1(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
HttpPostedFile file = FileUpload1.PostedFile;
BinaryReader br = new BinaryReader(file.InputStream);
byte[] buffer = br.ReadBytes(file.ContentLength);
using (UpLoadDatabase1Entities uc = new UpLoadDatabase1Entities())
{
uc.UploadedFiles.Add(
new UploadedFile
{
FileName =file.FileName,
ContentType=file.ContentType,
FileID=0,
FileSize=file.ContentLength,
FileExtension=Path.GetExtension(file.FileName),
FileContent = buffer
});
uc.SaveChanges();
PopulateUploadedFiles();
}
}
}
}
}
資料庫:
CREATE TABLE [dbo].[UploadedFile] (
[FileID] INT NOT NULL,
[FileName] VARCHAR (200) NOT NULL,
[FileSize] INT NOT NULL,
[ContentType] VARCHAR (200) NOT NULL,
[FileExtension] VARCHAR (10) NOT NULL,
[FileContent] VARBINARY (MAX) NOT NULL,
PRIMARY KEY CLUSTERED ([FileID] ASC)
);
目前暫時找不到問題所在,還請各位為我解答,謝謝。
依據你參考的文章
資料表的部份改成如下
CREATE TABLE [dbo].[UploadedFile] (
[FileID] INT NOT NULL,
[FileName] VARCHAR (200) NOT NULL,
[FileSize] INT NOT NULL,
[ContentType] VARCHAR (200) NOT NULL,
[FileExtension] VARCHAR (10) NOT NULL,
[FileContent] VARBINARY (MAX) NOT NULL
);