2009-02-21 5 views

risposta

3

Se si è interessati all'uso del database per l'archiviazione dei file, consultare this 4guysfromrolla article. È orientato al web, ma non dovrebbe esserci alcun problema a trovare ciò di cui hai bisogno.

3

Per inserirlo nel database, è necessario leggerlo in un array di byte. O leggerlo dal file system o utilizzare la proprietà AspNetFileUploadWebControl.FileBytes. Creare una procedura di inserimento memorizzato e aggiungere l'array di byte come parametro per la colonna DB (la colonna deve essere del tipo di dati SQL "immagine").

per farlo fuori del database, usare qualcosa come:

theRow = getDatarowFromDatabase(); 
aByteArrayOfTheFile = (byte[])theRow["theSqlImageColumnWithTheFileInIt"]; 

Per consentire all'utente di visualizzare o scaricare esso uso il mio metodo SendAsFileToBrowser():

SendAsFileToBrowser(aByteArrayOfTheFile, "application/pdf", "downloaded.pdf"); 

Il codice sorgente per il metodo (con sovraccarico):

// Stream a binary file to the user's web browser so they can open or save it. 
    public static void SendAsFileToBrowser(byte[] File, string Type, string FileName) 
    { 
     string disp = "attachment"; 
     if (string.IsNullOrEmpty(FileName)) 
     { 
      disp = "inline"; 
     } 

     // set headers 
     var r = HttpContext.Current.Response; 
     r.ContentType = Type; // eg "image/Png" 
     r.Clear(); 
     r.AddHeader("Content-Type", "binary/octet-stream"); 
     r.AddHeader("Content-Length", File.Length.ToString()); 
     r.AddHeader("Content-Disposition", disp + "; filename=" + FileName + "; size=" + File.Length.ToString()); 
     r.Flush(); 

     // write data to requesting browser 
     r.BinaryWrite(File); 
     r.Flush(); 
    } 
    //overload 
    public static void SendAsFileToBrowser(byte[] File, string Type) 
    { 
     SendAsFileToBrowser(File, Type, ""); 
    } 
    // overload 
    public static void SendAsFileToBrowser(System.IO.Stream File, string Type, string FileName) 
    { 
     byte[] buffer = new byte[File.Length]; 
     int length = (int)File.Length; 
     File.Write(buffer, 0, length - 1); 
     SendAsFileToBrowser(buffer, FileName, Type); 
    }