C#多文件上传

问题描述:

我有这个工作代码上传图片到MySQL表,工作正常,但我想知道我能做些什么来转换这一个文件上传到多个文件上传。我知道我需要一个,但我不知道到底应该在哪里。C#多文件上传

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> 
+0

当我尝试使用PostedFiles时,我得到一个错误,我认为它是因为我使用3.5框架,让我添加这个到我的问题。 –

+0

@ F.Flores https://www.microsoft.com/en-us/download/details.aspx?id=30653 – mxmissile

+0

服务器仅适用于3.5或更低版本,我无法改变它。 –