【问题标题】:c# upload file to stream?c#将文件上传到流?
【发布时间】:2011-12-11 06:22:10
【问题描述】:

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

这是目前为止的代码:

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


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

        }

【问题讨论】:

标签: c# asp.net upload stream web


【解决方案1】:

你可以这样做

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

希望对你有帮助……

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      FileUpload.PostedFile 返回的对象有一个InputStream property,你可以从中读取上传的文件数据。

      【讨论】:

        猜你喜欢
        • 2011-03-05
        • 1970-01-01
        • 1970-01-01
        • 2012-07-11
        • 1970-01-01
        • 2018-03-20
        • 1970-01-01
        • 1970-01-01
        • 2016-03-14
        相关资源
        最近更新 更多