我有这个工作代码将图像上传到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
答案 0 :(得分:0)
遍历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>