我希望用户上传一个文件并将其保存到流。
下面是到目前为止的代码: private void Submit_ServerClick(object sender, System.EventArgs e)
{
fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
}
你可以这样做
string filePath = uploadFile(fileUploadControl.FileContent);
private string uploadFile(Stream serverFileStream)
{
string filename = ConfigurationManager.AppSettings["FileUploadTempDir"] +
DateTime.Now.ToString("yyyyMMddhhmm") + "_" +
Customer.GetCustomerName(CustomerId).Replace(" ", "_") + ".txt";
try
{
int length = 256;
int bytesRead = 0;
Byte[] buffer = new Byte[length];
// write the required bytes
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
do
{
bytesRead = serverFileStream.Read(buffer, 0, length);
fs.Write(buffer, 0, bytesRead);
}
while (bytesRead == length);
}
serverFileStream.Dispose();
return filename;
}
catch (Exception ex)
{
lblErrorMessage.Text += "An unexpeded error occured uploading the file. " + ex.Message;
return string.Empty;
}
}
FileUpload.PostedFile
返回的对象具有InputStream
属性,您可以从中读取上传的文件数据
看起来像这个http://support.microsoft.com/kb/323246
string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
string SaveLocation = Server.MapPath("Data") + "\" + fn;
try
{
File1.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch ( Exception ex )
{
Response.Write("Error: " + ex.Message);
//Note: Exception.Message returns a detailed message that describes the current exception.
//For security reasons, we do not recommend that you return Exception.Message to end users in
//production environments. It would be better to put a generic error message.
}