[英]C# Multiple File Upload
我有此工作代码可以将图像上传到MySQL表中,但工作正常,但我想知道如何将该文件上传转换为多文件上传。 我知道我需要一个,但我不知道确切在哪里。
protected void UploadFile(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
int alerta = Convert.ToInt32(this.alertatxt.Text);
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO foto(FileName, ContentType, Content, IdAlerta) VALUES (@FileName, @ContentType, @Content, @alerta)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@FileName", filename);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Content", bytes);
cmd.Parameters.AddWithValue("@alerta", alerta);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
另外,如果有人可以帮助我验证文件类型,然后再上传,例如输入仅允许.png,.jpg等。
编辑:
我正在使用.NET Framework 3.5
循环访问FileUpload1.PostedFiles
,以使用path.GetExtension(fileName)
来验证文件扩展名,或者可以限制iis上的文件mime类型上载。
说明文件:
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.postedfiles.aspx
编辑:对于低于4.5的.Net框架,请通过ajax上传文件,然后在服务器端
var fileCollection = Request.Files;
for (int i = 0; i < fileCollection.Count; i++)
{
HttpPostedFile upload = fileCollection[i];
//Do your stuff
}
客户端:
function uploadFiles()
{
var inputElement = document.getElementById("FileUpload1");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText) {
alert("upload done!");
}
else {
alert("upload failed!");
}
};
xhr.open('POST', "WebForm1.aspx/upload");
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.send(inputElement.Files);
}
HTML:
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true"/>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="uploadFiles()" />
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.