Hello I'm trying to create a multiple file upload with C#, at the moment I can upload only one but I need to upload more than one, another thing is that I have to show a preview of the file (only images), I have code for a multiple file upload but only works in framework 4+ and my app is in 3.5, I'm thinking about using a foreach or something like that but I'm not sure so I hope you can help me, here is my C# method for file upload:
protected void UploadFile(object sender, EventArgs e)
{
if (FileUpload1.HasFile && this.alertatxt.Text != "" && this.pietxt.Text != "")
{
string extension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (extension == ".jpg" || extension == ".png" || extension == ".jpeg")
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
int alerta = Convert.ToInt32(this.alertatxt.Text);
string pie = this.pietxt.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, PieFoto) VALUES (@FileName, @ContentType, @Content, @alerta, @pie)";
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);
cmd.Parameters.AddWithValue("@pie", pie);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Uploaded.');", true);
}
}
this.pietxt.Text = "";
}
}
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('File must be .jpg . png .jpeg');", true);
this.pietxt.Text = "";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Fill all the fields.');", true);
this.alertatxt.Focus();
this.pietxt.Text = "";
}
}
EDIT: Image preview is not much important but however here is the code:
<div class="col-md-6 text-center form-group">
<asp:FileUpload ID="FileUpload1" runat="server" onchange="showimagepreview(this)" />
</div>
<div class="col-md-6 text-center form-group">
<img id="img" alt="" class="img-responsive" style="width: 300px" />
</div>
JS:
<script type="text/javascript">
function showimagepreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>