你好我想創建一個多文件上傳與C#,此刻我只能上傳一個,但我需要上傳多個,另一件事是我必須顯示該文件的預覽(只有圖像),我有一個多文件上傳的代碼,但只適用於框架4 +和我的應用程序在3.5,我想使用一個foreach或類似的東西,但我不知道所以我希望你能幫助我,這裏是文件上傳我的C#方法:轉換文件上傳到多個文件上傳c#
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 = "";
}
}
編輯:圖像預覽並不多重要,但在這裏卻是代碼:
個<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>
我要去檢查信息也是我在考慮使用通用處理器,感謝兄弟。 –