Upload di un file: esempio completo

FAQ di programmazione in .NET

Upload di un file: esempio completo

Messaggioda alesslud » ven ott 30, 2009 2:37 pm

Vi mostriamo un esempio completo di upload di un file da una pagina web: l'esempio esegue l'upload sia sul file system che su un db MySql.
Allegati
FileUpload.zip
(86.13 KiB) Scaricato 272 volte
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

Default.aspx

Messaggioda alesslud » ven ott 30, 2009 2:39 pm

<%@ Page language="c#" AutoEventWireUp="false" Codebehind="default.aspx.cs" Inherits="FileUpload.WebForm1" Src="default.aspx.cs" %>

<html>
<head><title>File Upload to MySql</title></head>
<body>
<form id="Form1" method="post" runat="server" enctype="multipart/form-data">
<asp:label id="lblFile" runat="server" Font-Bold="True">Picture:</asp:label>
<input id="filMyFile" type="file" runat="server" />
<p></p>
<asp:button id="cmdSend" runat="server" Text="Send"/>
<p></p>
<asp:Label id="lblInfo" runat="server" Font-Bold="True" Visible="false"></asp:Label>
<p></p>
<table>
<tr>
<td>
<asp:Label id="lblText1" runat="server" Font-Bold="True" Visible="false">This was stored as file</asp:Label>
</td>
<td>
<asp:Label id="lblText2" runat="server" Font-Bold="True" Visible="false">This was stored in database</asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Image id="imgFile" runat="server" Visible="False"></asp:Image>
</td>
<td>
<asp:Image id="imgDB" runat="server" Visible="False"></asp:Image>
</td>
</tr>
</table>
</form>
</body>
</html>
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

Default.aspx.cs

Messaggioda alesslud » ven ott 30, 2009 2:39 pm

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data;
using System.Data.OleDb;
using MySql.Data.MySqlClient;

namespace FileUpload
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class WebForm1 : System.Web.UI.Page
{ protected Label lblFile;
protected HtmlInputFile filMyFile;
protected System.Web.UI.WebControls.Label lblInfo;
protected System.Web.UI.WebControls.Button cmdSend;
protected System.Web.UI.WebControls.Image imgFile;
protected System.Web.UI.WebControls.Image imgDB;
protected System.Web.UI.WebControls.Label lblText1;
protected System.Web.UI.WebControls.Label lblText2;

override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
this.cmdSend.Click += new System.EventHandler(this.cmdSend_Click);
}

private void Page_Load(object sender, System.EventArgs e)
{
// Verifica se la chiave primaria è passata come parametro
if( Request.QueryString["FileID"] != null )
{
// Carica il file dal database per visualizzarlo su una pagina web
String pippo = Request.QueryString["FileID"];
ShowTheFile(Convert.ToInt32(Request.QueryString["FileID"]));
}
}

private void cmdSend_Click(object sender, System.EventArgs e)
{
// Verifica se il file è stato inviato
if( filMyFile.PostedFile != null )
{
// Prendo la refernce al file inviato
HttpPostedFile myFile = filMyFile.PostedFile;
// Prendo la grandezza del file inviato
int nFileLen = myFile.ContentLength;
// verifico che la grandezza sia maggiore > 0
if( nFileLen > 0 )
{
// Alloco il buffer per la lettura del file
byte[] myData = new byte[nFileLen];

// Leggo il file inviato da un Stream
myFile.InputStream.Read(myData, 0, nFileLen);
string strFilename = Path.GetFileName(myFile.FileName);
this.writeToFileSystem(Server.MapPath(strFilename), ref myData);

// Salvo il file sul database
Object nFileID1 = this.writeToDBMySql(strFilename, myFile.ContentType, ref myData);
lblInfo.Text =
"Filename: " + strFilename + "<br>" +
"Size: " + nFileLen.ToString() + "<p>";


// imposto l'url del file salvato
imgFile.ImageUrl = strFilename;
imgFile.ToolTip = "Questo file è stato salvato sul file system.";
lblText1.Text = imgFile.ImageUrl;

// Set URL dell'oggetto per puntare all'id del file
// per poterlo riprendere dal database
imgDB.ImageUrl = GetMyName() + "?FileID=" + nFileID1.ToString();
imgDB.ToolTip = "Questo file è stato salvato sul database.";
lblText2.Text = imgDB.ImageUrl;

// visualizzo tutto
imgFile.Visible = true;
imgDB.Visible = true;
lblText1.Visible = true;
lblText2.Visible = true;
}
}
}

// Scrive il file nella directory corrente
private void writeToFileSystem(string strPath, ref byte[] Buffer)
{
// Creo il file
FileStream newFile = new FileStream(strPath, FileMode.Create);

// Scrivo il file sul file system
newFile.Write(Buffer, 0, Buffer.Length);

// Chiudo il file
newFile.Close();
}


private Object writeToDBMySql(string strName, string strType, ref byte[] Buffer)
{
ConnectionMysql mySql = new ConnectionMysql();
MySqlConnection conn = mySql.getConnection();
Object nFileID = 0;
MySqlDataAdapter dbAdapt = new MySqlDataAdapter("SELECT * FROM immaginitest", conn);
MySqlCommandBuilder dbCB = new MySqlCommandBuilder(dbAdapt);
DataSet dbSet = new DataSet();

// Popolo il DataSet con i dati
dbAdapt.Fill(dbSet, "immaginitest");

// Punto alla tabella
DataTable dbTable = dbSet.Tables["immaginitest"];

// Crea una nuova riga sul db
DataRow dbRow = dbTable.NewRow();

// Salva i dati
dbRow["FileName"] = strName;
dbRow["FileSize"] = Buffer.Length;
dbRow["ContentType"] = strType;
dbRow["FileData"] = Buffer;

// Add row back to table
dbTable.Rows.Add(dbRow);

// Esegue l'update
dbAdapt.Update(dbSet, "immaginitest");

// Ottengo il FileId creato
if (!dbRow.IsNull("FileID"))
nFileID = dbRow["FileID"];

// chiudo la connessione
conn.Close();

// Return FileID
return nFileID;
}

// Legge il file dal Database e lo visulizza su un Browser
private void ShowTheFile(int FileID)
{
string SQL = "SELECT FileSize, FileData, ContentType FROM immaginitest WHERE FileID = "
+ FileID.ToString();

ConnectionMysql mySql = new ConnectionMysql();
MySqlConnection conn = mySql.getConnection();
MySqlCommand dbComm = new MySqlCommand(SQL, conn);
MySqlDataReader dbRead = dbComm.ExecuteReader();
dbRead.Read();
Response.Clear();
Response.ContentType = (string)dbRead["ContentType"];

// Scrivo il file in un Output Stream
Response.OutputStream.Write((byte[])dbRead["FileData"], 0, Convert.ToInt32(dbRead["FileSize"].ToString()));
conn.Close();
Response.End();
}

private string GetMyName()
{
string strScript = Request.ServerVariables["SCRIPT_NAME"];
int nPos = strScript.LastIndexOf("/");
if( nPos > -1 )
strScript = strScript.Substring(nPos + 1);
return strScript;
}
}
}
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

MySqlConnection.java

Messaggioda alesslud » ven ott 30, 2009 2:39 pm

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MySql.Data.MySqlClient;

// Copyright (C) 2004-2005 MySQL AB
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as published by
// the Free Software Foundation
//
// There are special exceptions to the terms and conditions of the GPL
// as it is applied to this software. View the full text of the
// exception in file EXCEPTIONS in the directory of this software
// distribution.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA


/// <summary>
/// Summary description for Form1.
/// </summary>
public class ConnectionMysql
{
/*string connStr = String.Format("Server=Localhost;Database=Sql23503_1;Uid=root;Pwd=betati",
"", "", "");*/
string connStr = String.Format("Server=localhost;Database=Sql23503_1;Uid=root;Pwd=betati",
"", "", "");
public MySqlConnection getConnection()
{
MySqlConnection conn = null;
if (conn != null)
conn.Close();
try
{
conn = new MySqlConnection();
//conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

conn = new MySqlConnection(connStr);

conn.Open();
}
catch (MySqlException ex)
{
Console.WriteLine("Error connecting to the server: " + ex.Message);
}
return conn;
}
}
Allegati
MysqlReference.zip
Per poter funzionare bisogna importare le librerie MySql
(80.3 KiB) Scaricato 267 volte
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

Web.config (.NET 2.0)

Messaggioda alesslud » ven ott 30, 2009 2:42 pm

<?xml version="1.0"?>
<configuration>
<system.web>
<customErrors mode="Off"/>
<httpHandlers>

</httpHandlers>
<compilation debug="true"/>
</system.web>
<appSettings>
</appSettings>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=localhost;Database=yourdbname;User ID=youruser;Password=yourpassword;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="MappaViewAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<yyyyyy>
<service name="MappaView">
<endpoint address="" behaviorConfiguration="MappaViewAspNetAjaxBehavior"
binding="webHttpBinding" contract="MappaView" />
</service>
</yyyyyy>
</system.serviceModel>
</configuration>
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am

Script di creazione delle tabelle

Messaggioda alesslud » ven ott 30, 2009 2:43 pm

CREATE TABLE `yourdbname`.`immaginitest` (
`FileName` varchar(45) NOT NULL DEFAULT '',
`FileSize` varchar(45) NOT NULL DEFAULT '',
`ContentType` varchar(250) NOT NULL DEFAULT '',
`FileData` mediumblob,
`FileId` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`FileId`)
) ENGINE=InnoDB AUTO_INCREMENT=1;
alesslud
Site Admin
 
Messaggi: 779
Iscritto il: mer nov 08, 2006 8:09 am


Torna a .NET

Chi c’è in linea

Visitano il forum: Nessuno e 1 ospite

cron