I am using libcurnet for posting some fields and html or pdf file to server. I post fields but can not upload file to server. Here is my code :
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); } }
I don't know where is the problem.
Try using fiddler2 to spy on the TCP stream, particularly the header part, and compare it to performing a manual upload from your browser.
I suppose that the library itself you have downloaded from here. If so, try to use upload sample from /samples/FileUpload.cs
Something like this.
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");
Don't forget to change "upload_max_filesize" in php.ini on server for files more then 2Mb.
In file "uploader.php" you need writing something like this.
<?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]";
}
?>
精彩评论