我修改了一个文件上传项目&下载到&从SQL服务器使用C#按照我的要求添加三个文本框。我能够在SQL服务器上传文件,并可以使用以下页面查看文件
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Uploaded Files</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="odsFiles" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" SortExpression="Id" />
<asp:BoundField DataField="OriginalName" HeaderText="OriginalName" SortExpression="OriginalName" />
<asp:BoundField DataField="ContentType" HeaderText="ContentType" SortExpression="ContentType" />
<asp:BoundField DataField="DateCreated" HeaderText="DateCreated" SortExpression="DateCreated" />
<asp:BoundField DataField="Equipment" HeaderText="Equipment" SortExpression="Equipment" />
<asp:BoundField DataField="Uploadedby" HeaderText="Uploaded by" SortExpression="Uploadedby" />
<asp:BoundField DataField="Letter_date" HeaderText="Letter Dated" SortExpression="Letter_date" />
<asp:HyperLinkField DataNavigateUrlFields="Id" DataNavigateUrlFormatString="~/DownloadFile.aspx?Id={0}" HeaderText="Download" Text="Download" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:HyperLink ID="lnkView" runat="server" NavigateUrl='<%# Eval("Id", "~/ViewFile.aspx?Id={0}") %>' Text="View"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<br />
<asp:Button ID="btnAddNew" runat="server" OnClick="btnAddNew_Click" Text="Add New File" /><br />
<br />
<br />
<asp:ObjectDataSource ID="odsFiles" runat="server" SelectMethod="GetList" TypeName="FileInfo" />
</div>
</form>
</body>
</html>
这没有问题,我无法修改项目的下载部分,因为最初项目是使用Id = uniqueidentifier开发的,我已将其更改为Int。此文件中的Perhapes问题(downloadfile.aspx.cs):
using System;
using System.IO;
public partial class DownloadFile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString.Get("Id") != null)
{
Response.Clear();
int id = new int(Request.QueryString.Get("Id"));
File myFile = File.GetItem(id);
Response.ContentType = "application/x-unknown";
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + myFile.OriginalName + "\"");
if (myFile.ContainsFile)
{
Response.BinaryWrite(myFile.FileData);
}
else
{
Response.WriteFile(Path.Combine(AppConfiguration.UploadsFolder, myFile.FileUrl));
}
}
else
{
Response.Redirect("~/");
}
}
}
第二个文件(File.cs)如下:
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.IO;
/// <summary>
/// The File class abstracts behavior for uploaded files that are stored in a datastore.
/// It allows you to save an uploaded file in the datastore and retrieve it again.
/// </summary>
[DataObject()]
public class File
{
#region Private Variables
private Int32 id;
private string fileUrl;
private byte[] fileData;
private string contentType;
private string originalName;
private DateTime dateCreated;
private bool containsFile;
#endregion
#region Public Properties
/// <summary>
/// Gets the unique id of the uploaded file.
/// This ID is used as the file name when files are stored in the file system.
/// </summary>
public Int32 Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the date and time the file was uploaded.
/// </summary>
public DateTime DateCreated
{
get
{
return dateCreated;
}
}
/// <summary>
/// Gets the content type of the file.
/// </summary>
public string ContentType
{
get
{
return contentType;
}
}
/// <summary>
/// Gets the original name of the file.
/// </summary>
public string OriginalName
{
get
{
return originalName;
}
}
/// <summary>
/// Gets the virtual URL of the file.
/// When this property does not contain data, then <see cref="FileData"/> contains
/// a byte array with the actual file.
/// </summary>
public string FileUrl
{
get
{
return fileUrl;
}
}
/// <summary>
/// Gets the file data.
/// When this property does not contain data, then <see cref="FileUrl"/> contains
/// the virtual path to the file starting from the Uploads folder.
/// </summary>
public byte[] FileData
{
get
{
return fileData;
}
}
/// <summary>
/// Gets a value indicating whether this instance contains the actual file data.
/// When ContainsFile is true, it means the actual file is held in <see cref="FileData"/>.
/// When ContainsFile is false, then <see cref="FileUrl"/> contains the virtual path
/// to the file on disk.
/// </summary>
public bool ContainsFile
{
get
{
return containsFile;
}
}
#endregion
#region Public Methods
/// <summary>
/// Gets a file from the datastore.
/// </summary>
/// <param name="fileId">The ID of the file.</param>
public static File GetItem(Guid fileId)
{
File myFile = null;
using (SqlConnection mySqlConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
SqlCommand myCommand = new SqlCommand("sprocFilesSelectSingleItem", mySqlConnection);
myCommand.CommandType = CommandType.StoredProcedure;
SqlParameter prmId = new SqlParameter("@id", SqlDbType.Int);
prmId.Value = fileId;
myCommand.Parameters.Add(prmId);
mySqlConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
if (myReader.Read())
{
myFile = new File(myReader);
}
myReader.Close();
}
mySqlConnection.Close();
}
return myFile;
}
/// <summary>
/// Saves a file to the database.
/// </summary>
/// <returns>Returns true when the file was stored succesfully, or false otherwise.</returns>
public bool Save()
{
return Save(DataStoreType.Database, String.Empty);
}
/// <summary>
/// Saves a file to the file system.
/// This method also saves the meta data of the file to the database.
/// </summary>
/// <param name="filePath">The location and name of the file that is to be saved.</param>
/// <returns>
/// Returns true when the file was stored succesfully, or false otherwise.
/// </returns>
public bool Save(string filePath)
{
return Save(DataStoreType.FileSystem, filePath);
}
/// <summary>
/// Saves a file to the database and optionally to disk.
/// </summary>
/// <returns>Returns true when the file was stored succesfully, or false otherwise.</returns>
private bool Save(DataStoreType dataStoreType, string filePath)
{
using (SqlConnection mySqlConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
// Set up the Command object
SqlCommand myCommand = new SqlCommand("sprocFilesInsertSingleItem", mySqlConnection);
myCommand.CommandType = CommandType.StoredProcedure;
// Set up the ID parameter
SqlParameter prmId = new SqlParameter("@id", SqlDbType.Int);
prmId.Value = id;
myCommand.Parameters.Add(prmId);
// Set up the FileUrl parameter
SqlParameter prmFileUrl = new SqlParameter("@fileUrl", SqlDbType.NVarChar, 255);
// If we need to store the file on disk, save the fileUrl.
if (dataStoreType == DataStoreType.FileSystem)
{
prmFileUrl.Value = fileUrl;
}
else
{
prmFileUrl.Value = DBNull.Value;
}
myCommand.Parameters.Add(prmFileUrl);
// Set up the FileData parameter
SqlParameter prmFileData = new SqlParameter("@fileData ", SqlDbType.VarBinary);
// If we need to store the file in the database,
// pass in the actual file bytes.
if (dataStoreType == DataStoreType.Database)
{
prmFileData.Value = fileData;
prmFileData.Size = fileData.Length;
}
else
{
prmFileData.Value = DBNull.Value;
}
myCommand.Parameters.Add(prmFileData);
// Set up the OriginalName parameter
SqlParameter prmOriginalName = new SqlParameter("@originalName", SqlDbType.NVarChar, 50);
prmOriginalName.Value = originalName;
myCommand.Parameters.Add(prmOriginalName);
// Set up the ContentType parameter
SqlParameter prmContentType = new SqlParameter("@contentType", SqlDbType.NVarChar, 50);
prmContentType.Value = contentType;
myCommand.Parameters.Add(prmContentType);
// Execute the command, and clean up.
mySqlConnection.Open();
bool result = myCommand.ExecuteNonQuery() > 0;
mySqlConnection.Close();
// Database update is done; now store the file on disk if we need to.
if (dataStoreType == DataStoreType.FileSystem)
{
const int myBufferSize = 1024;
Stream myInputStream = new MemoryStream(fileData);
Stream myOutputStream = System.IO.File.OpenWrite(filePath);
byte[] buffer = new Byte[myBufferSize];
int numbytes;
while ((numbytes = myInputStream.Read(buffer, 0, myBufferSize)) > 0)
{
myOutputStream.Write(buffer, 0, numbytes);
}
myInputStream.Close();
myOutputStream.Close();
}
return result;
}
}
#endregion
#region Constructor(s)
/// <summary>
/// Initializes a new instance of the <see cref="File"/> class with the data from the SqlDataReader.
/// </summary>
/// <param name="myReader">A SqlDataReader that contains the data for this file.</param>
public File(SqlDataReader myReader)
{
id = myReader.Int32(myReader.GetOrdinal("Id"));
dateCreated = myReader.GetDateTime(myReader.GetOrdinal("DateCreated"));
originalName = myReader.GetString(myReader.GetOrdinal("OriginalName"));
contentType = myReader.GetString(myReader.GetOrdinal("ContentType"));
if (!myReader.IsDBNull(myReader.GetOrdinal("FileData")))
{
fileData = (byte[])myReader[myReader.GetOrdinal("FileData")];
containsFile = true;
}
else
{
fileUrl = myReader.GetString(myReader.GetOrdinal("FileUrl"));
containsFile = false;
}
}
/// <summary>
/// Initializes a new instance of the File class with the data from the incoming parameters.
/// </summary>
/// <param name="contentType">The content type of the file, like image/pjpeg or image/gif.</param>
/// <param name="originalName">The original name of the uploaded file.</param>
/// <param name="fileData">A byte array with the actual file data.</param>
public File(string contentType, string originalName, byte[] fileData)
{
this.id = Convert.ToInt32;
this.contentType = contentType;
this.fileData = fileData;
this.originalName = originalName;
string extension = Path.GetExtension(originalName);
string fileName = this.Id.ToString() + extension;
this.fileUrl = fileName;
}
#endregion
}
我收到错误&#34;编译器错误消息:CS1061:&#39; System.Data.SqlClient.SqlDataReader&#39;不包含&#39; Int32&#39;的定义没有扩展方法&#39; Int32&#39;接受类型&System; System.Data.SqlClient.SqlDataReader&#39;的第一个参数。可以找到(你是否错过了使用指令或汇编引用?)&#34;在&#39; File.cs&#39;。请帮忙。
答案 0 :(得分:1)
变化: -
id = myReader.Int32(myReader.GetOrdinal("Id"));
到
id = myReader.GetInt32(myReader.GetOrdinal("Id"));
在File
构造函数中,SqlDataReader
不包含Int32
的定义,您的异常消息是不言自明的。
答案 1 :(得分:0)
试试这个
int index;
if (_sqlreader.HasRows)
{
index = _sqlreader.GetOrdinal("ColumnName");
if (!_sqlreader.IsDBNull(index))
return _sqlreader.GetInt32(index);
}