在asp.net中上传文件c#

时间:2011-02-28 12:00:35

标签: c# asp.net asp.net-3.5

嘿伙计们,使用api“Bits on the Run”以下是上传AP​​I的代码

   public string Upload(string uploadUrl, NameValueCollection args, string filePath) 
   {
        _queryString = args; //no required args

        WebClient client = createWebClient();
        _queryString["api_format"] = APIFormat ?? "xml"; //xml if not specified - normally set in required args routine                                   
        queryStringToArgs();

        string callUrl = _apiURL + uploadUrl + "?" + _args;
        callUrl = uploadUrl + "?" + _args;

        try {
             byte[] response = client.UploadFile(callUrl, filePath);
             return Encoding.UTF8.GetString(response);     
        } catch {
            return "";
        }   
    }

以下是我上传文件的代码,m使用FileUpload控件获取文件的完整路径(但是没有成功)...

            botr = new BotR.API.BotRAPI("key", "secret_code");   
            var response = doc.Descendants("link").FirstOrDefault();
            string url = string.Format("{0}://{1}{2}", response.Element("protocol").Value, response.Element("address").Value, response.Element("path").Value);
            //here i want fullpath of the file, how can i achieve that here
            string filePath = fileUpload.PostedFile.FileName;//"C://Documents and Settings//rkrishna//My Documents//Visual Studio 2008//Projects//BitsOnTheRun//BitsOnTheRun//rough_test.mp4";

            col = new NameValueCollection();

            FileStream fs = new FileStream(filePath, FileMode.Open);

            col["file_size"] = fs.Length.ToString();
            col["file_md5"] = BitConverter.ToString(HashAlgorithm.Create("MD5").ComputeHash(fs)).Replace("-", "").ToLower();
            col["key"] = response.Element("query").Element("key").Value;
            col["token"] = response.Element("query").Element("token").Value;

            fs.Dispose();
            string uploadResponse = botr.Upload(url, col, filePath);

我在一些论坛中读到,为了某些安全目的,你无法从客户端获得文件的完整路径。如果是真的那么我怎样才能在我的场景中实现文件上传?

1 个答案:

答案 0 :(得分:1)

是的,这是真的,出于安全原因你无法获得客户端机器的完整路径,你可以做的是,尝试以下,

      Stream stream = fileUpload.PostedFile.InputStream;
      stream.Read(bytes, 0, fileUpload.PostedFile.ContentLength);

而不是创建自己的FileStream使用FileUploadControl提供的流。 Ho它应该有所帮助。