无法使用libcurl.net上传http文件

时间:2011-03-20 22:46:00

标签: c# asp.net file-upload libcurl

我正在使用libcurnet将一些字段和html或pdf文件发布到服务器。我发布字段但无法将文件上传到服务器。这是我的代码:

  

public static void Main(String [] args)   {try {       Curl.GlobalInit((int)的CURLinitFlag.CURL_GLOBAL_ALL);

FileStream fs = new
FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.Read);

Easy easy = new Easy();

Easy.ReadFunction rf = new Easy.ReadFunction(OnReadData);
easy.SetOpt(CURLoption.CURLOPT_READFUNCTION,rf);

easy.SetOpt(CURLoption.CURLOPT_UPLOAD, true);
easy.SetOpt(CURLoption.CURLOPT_PUT, true);
easy.SetOpt(CURLoption.CURLOPT_URL, args[1]);

easy.SetOpt(CURLoption.CURLOPT_READDATA, fs);
easy.SetOpt(CURLoption.CURLOPT_INFILESIZE, fs.Length);

Easy.DebugFunction df = new Easy.DebugFunction(OnDebug);
easy.SetOpt(CURLoption.CURLOPT_DEBUGFUNCTION, df);
easy.SetOpt(CURLoption.CURLOPT_VERBOSE, true);

Easy.ProgressFunction pf = new Easy.ProgressFunction(OnProgress);
easy.SetOpt(CURLoption.CURLOPT_PROGRESSFUNCTION, pf);

Easy.WriteFunction wf = new Easy.WriteFunction(OnWriteData);
easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf);
easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS, args[2]);

easy.SetOpt(CURLoption.CURLOPT_USERAGENT, "Mozilla 4.0 (compatible; MSIE 6.0; Win32");
easy.SetOpt(CURLoption.CURLOPT_FOLLOWLOCATION, true);

easy.SetOpt(CURLoption.CURLOPT_POST, true);
easy.SetOpt(CURLoption.CURLOPT_VERBOSE, 1);
easy.SetOpt(CURLoption.CURLOPT_STDERR, 0);

easy.Perform();
easy.Cleanup();

fs.Close();
Curl.GlobalCleanup();    }    catch (Exception ex)    {
  Console.WriteLine(ex);    }  }

我不知道问题出在哪里。

2 个答案:

答案 0 :(得分:0)

尝试使用fiddler2监视TCP流,特别是标题部分,并将其与从浏览器执行手动上传进行比较。

答案 1 :(得分:0)

我想你已经从here下载了库本身。如果是这样,请尝试使用 /samples/FileUpload.cs

中的上传示例

像这样。

        MultiPartForm mf = new MultiPartForm();        

        // <input type="File" name="f1">
        mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "uploadedfile",
            CURLformoption.CURLFORM_FILE, "C:\\My Files\myUploadFile.exe",
            CURLformoption.CURLFORM_CONTENTTYPE, "application/binary",
            CURLformoption.CURLFORM_END);

        Easy easy = new Easy();
        easy.SetOpt(CURLoption.CURLOPT_HTTPPOST, mf);
        easy.SetOpt(CURLoption.CURLOPT_URL, "localhost/uploader.php");

不要忘记在服务器上的php.ini中更改“upload_max_filesize”以获取超过2Mb的文件。

在文件“uploader.php”中你需要写这样的东西。

<?php
  $target_path = "/uploaded/". basename( $_FILES["uploadedfile"]["name"]);
  if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target_path)) 
  {     
    echo "[File Upload Successful]";
  } 
  else
  {
    echo "[File Upload Error]";
  }
?>