繁体   English   中英

C#上传文件流?

[英]c# upload file to stream?

我希望用户上传文件并将其保存到流中。

这是到目前为止的代码:

 private void Submit_ServerClick(object sender, System.EventArgs e)
        {


               fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);

        }

FileUpload.PostedFile返回的对象具有InputStream属性,您可以从中读取上载的文件数据。

你可以这样

  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;
  }
}

我希望它将对您有帮助...

看起来像这样一个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. 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM