/// <summary> /// add information to upload a file, also perform check of file size and file existing /// </summary> private bool AddFormFile(LibCurl.MultiPartForm mf, string fileName, string field) { if (fileName != "") { if (!DrutNETBase.FileExists(fileName)) { sendLogEvent("Can't find file : " + fileName + "\n", "Curl", Enums.MessageType.Error); return(false); } else if ((new FileInfo(fileName).Length / 1024) > Enums.MAXFILESIZEKB) { sendLogEvent(fileName + " size is bigger than limit (" + (Enums.MAXFILESIZEKB / 1024).ToString() + "MB)" + "\n", "Curl", Enums.MessageType.Error); return(false); } else { LibCurl.CURLFORMcode res = mf.AddSection(LibCurl.CURLformoption.CURLFORM_COPYNAME, field, LibCurl.CURLformoption.CURLFORM_FILE, fileName, LibCurl.CURLformoption.CURLFORM_END); if (res != LibCurl.CURLFORMcode.CURL_FORMADD_OK) { sendLogEvent("Can't add Curl file: " + res.ToString() + "\n", "Curl", Enums.MessageType.Error); return(false); } else { return(true); } } } return(false); }
public static void Main(String[] args) { try { Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); // <form action="http://mybox/cgi-bin/myscript.cgi // method="post" enctype="multipart/form-data"> MultiPartForm mf = new MultiPartForm(); // <input name="frmUsername"> mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "frmUsername", CURLformoption.CURLFORM_COPYCONTENTS, "testtcc", CURLformoption.CURLFORM_END); // <input name="frmPassword"> mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "frmPassword", CURLformoption.CURLFORM_COPYCONTENTS, "tcc", CURLformoption.CURLFORM_END); // <input name="frmFileOrigPath"> mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "frmFileOrigPath", CURLformoption.CURLFORM_COPYCONTENTS, args[1], CURLformoption.CURLFORM_END); // <input name="frmFileDate"> mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "frmFileDate", CURLformoption.CURLFORM_COPYCONTENTS, "08/01/2004", CURLformoption.CURLFORM_END); // <input type="File" name="f1"> mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "f1", CURLformoption.CURLFORM_FILE, args[1], CURLformoption.CURLFORM_CONTENTTYPE, "application/binary", CURLformoption.CURLFORM_END); Easy easy = new Easy(); 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.SetOpt(CURLoption.CURLOPT_URL, args[0]); easy.SetOpt(CURLoption.CURLOPT_HTTPPOST, mf); easy.Perform(); easy.Cleanup(); mf.Free(); Curl.GlobalCleanup(); } catch(Exception ex) { Console.WriteLine(ex); } }
private LibCurl.CURLFORMcode AddFormField(LibCurl.MultiPartForm mf, object fieldName, object Value) { LibCurl.CURLFORMcode res = mf.AddSection(LibCurl.CURLformoption.CURLFORM_COPYNAME, fieldName, LibCurl.CURLformoption.CURLFORM_COPYCONTENTS, Value, LibCurl.CURLformoption.CURLFORM_END); if (res != LibCurl.CURLFORMcode.CURL_FORMADD_OK) { sendLogEvent("Can't add Curl field: " + res.ToString() + "\n", "Curl", Enums.MessageType.Error); } return(res); }
/// <summary> /// Upload a file to Drupal using the form-file module and CURL /// </summary> /// <param name="localPath">Local file location</param> /// <param name="serverDirectory">Save to a specific directory in drupal</param> /// <returns> File ID or -1 if failed to upload</returns> public int FileUpload(string localPath, string serverDirectory) { // Use file form module string url = ServerURL + "file-form"; LibCurl.MultiPartForm mf = new LibCurl.MultiPartForm(); AddFormFile(mf, localPath, "files[file_upload]"); // Optional parameter - save to a different directory AddFormField(mf, serverDirectory, "file_directory"); AddFormField(mf, "form_token", getToken(url, "edit-file-form-upload-form-token")); AddFormField(mf, "form_id", "file_form_upload"); AddFormField(mf, "op", "Upload file"); EasyCurl.SetOpt(LibCurl.CURLoption.CURLOPT_HTTPPOST, mf); EasyCurl.SetOpt(LibCurl.CURLoption.CURLOPT_URL, url); _htmlDataIn = "";//clear html data in return LibCurl.CURLcode exec = DrupCurlPerform(); // Check if Json returned a file id int fileID; string ex = @"fid"":.""([^""]*)"; Regex rx = new Regex(ex); MatchCollection fields = rx.Matches(_htmlDataIn); if (fields.Count > 0) { fileID = Convert.ToInt32(fields[0].Groups[1].Captures[0].Value); } else { fileID = -1; } //JsonUtility.GenerateIndentedJsonText = false; string tempHttp = ""; EasyCurl.GetInfo(LibCurl.CURLINFO.CURLINFO_EFFECTIVE_URL, ref tempHttp); if (((fileID == -1)))// || (tempHttp == ServerURL + "file-form")) { sendLogEvent("Error uploading file, Curl error no: " + "\n", "Curl", Enums.MessageType.Error); } return(fileID); }
/// <summary> /// Set options for this object. See the <c>EasyGet</c> sample for /// basic usage. /// </summary> /// <param name="option">This should be a valid <see cref="CURLoption"/>.</param> /// <param name="parameter">This should be a parameter of a varying /// type based on the value of the <c>option</c> parameter.</param> /// <exception cref="System.NullReferenceException">This is thrown if /// the native <c>CURL*</c> handle wasn't created successfully.</exception> /// <returns>A <see cref="CURLcode"/>, typically obtained from /// <c>cURL</c> internally, but sometimes a /// <see cref="CURLcode.CURLE_BAD_FUNCTION_ARGUMENT"/> /// will be returned if the type of value of <c>parameter</c> is invalid. /// </returns> public CURLcode SetOpt(CURLoption option, Object parameter) { EnsureHandle(); CURLcode retCode = CURLcode.CURLE_OK; // numeric cases if ((int)option < CURLOPTTYPE_OBJECTPOINT) { int i = 0; if (option == CURLoption.CURLOPT_DNS_USE_GLOBAL_CACHE || option == CURLoption.CURLOPT_SOURCE_PORT) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } else if (option == CURLoption.CURLOPT_TIMEVALUE) { // unboxing may throw class cast exception //DateTime d = (DateTime)parameter; DateTime startTime = Main.DateTimeBegin; TimeSpan currTime = new TimeSpan(DateTime.Now.Ticks - startTime.Ticks); i = Convert.ToInt32(currTime.TotalSeconds); } else { i = Convert.ToInt32(parameter); } retCode = External.curl_easy_setopt_int(m_pCURL, option, i); } // object cases: the majority else if ((int)option < CURLOPTTYPE_FUNCTIONPOINT) { switch (option) { // various data items case CURLoption.CURLOPT_PRIVATE: m_privateData = parameter; break; case CURLoption.CURLOPT_WRITEDATA: m_writeData = parameter; break; case CURLoption.CURLOPT_READDATA: m_readData = parameter; break; case CURLoption.CURLOPT_PROGRESSDATA: m_progressData = parameter; break; case CURLoption.CURLOPT_DEBUGDATA: m_debugData = parameter; break; case CURLoption.CURLOPT_HEADERDATA: m_headerData = parameter; break; case CURLoption.CURLOPT_SSL_CTX_DATA: m_sslContextData = parameter; break; case CURLoption.CURLOPT_IOCTLDATA: m_ioctlData = parameter; break; // items that can't be set externally or // obsolete items case CURLoption.CURLOPT_ERRORBUFFER: case CURLoption.CURLOPT_STDERR: case CURLoption.CURLOPT_SOURCE_HOST: case CURLoption.CURLOPT_SOURCE_PATH: case CURLoption.CURLOPT_PASV_HOST: return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); // singular case for share case CURLoption.CURLOPT_SHARE: { Share share = parameter as Share; if (share == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } retCode = External.curl_easy_setopt_ptr(m_pCURL, option, share.GetHandle()); break; } // multipart HTTP post case CURLoption.CURLOPT_HTTPPOST: { MultiPartForm mf = parameter as MultiPartForm; if (mf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } retCode = External.curl_easy_setopt_ptr(m_pCURL, option, mf.GetHandle()); break; } // items curl wants as a curl_slist case CURLoption.CURLOPT_HTTPHEADER: case CURLoption.CURLOPT_PREQUOTE: case CURLoption.CURLOPT_QUOTE: case CURLoption.CURLOPT_POSTQUOTE: case CURLoption.CURLOPT_SOURCE_QUOTE: case CURLoption.CURLOPT_TELNETOPTIONS: case CURLoption.CURLOPT_HTTP200ALIASES: { Slist slist = parameter as Slist; if (slist == null) { retCode = External.curl_easy_setopt_ptr(m_pCURL, option, IntPtr.Zero); } else { retCode = External.curl_easy_setopt_ptr(m_pCURL, option, slist.GetHandle()); } break; } // string items default: { string s = parameter as string; if (s == null) { retCode = External.curl_easy_setopt_ptr(m_pCURL, option, IntPtr.Zero); } else { IntPtr pCurlStr = External.curl_shim_add_string( m_pMyStrings, s); if (pCurlStr != IntPtr.Zero) { retCode = External.curl_easy_setopt_ptr(m_pCURL, option, pCurlStr); } } break; } } } // FUNCTIONPOINT args, for delegates else if ((int)option < CURLOPTTYPE_OFF_T) { switch (option) { case CURLoption.CURLOPT_WRITEFUNCTION: { WriteFunction wf = parameter as WriteFunction; if (wf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfWrite = wf; break; } case CURLoption.CURLOPT_READFUNCTION: { ReadFunction rf = parameter as ReadFunction; if (rf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfRead = rf; break; } case CURLoption.CURLOPT_PROGRESSFUNCTION: { ProgressFunction pf = parameter as ProgressFunction; if (pf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfProgress = pf; break; } case CURLoption.CURLOPT_DEBUGFUNCTION: { DebugFunction pd = parameter as DebugFunction; if (pd == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfDebug = pd; break; } case CURLoption.CURLOPT_HEADERFUNCTION: { HeaderFunction hf = parameter as HeaderFunction; if (hf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfHeader = hf; break; } case CURLoption.CURLOPT_SSL_CTX_FUNCTION: { SSLContextFunction sf = parameter as SSLContextFunction; if (sf == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfSSLContext = sf; break; } case CURLoption.CURLOPT_IOCTLFUNCTION: { IoctlFunction iof = parameter as IoctlFunction; if (iof == null) { return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } m_pfIoctl = iof; break; } default: return(CURLcode.CURLE_BAD_FUNCTION_ARGUMENT); } } // otherwise, it's one of those 64-bit off_t guys! else { Int64 i = Convert.ToInt64(parameter); retCode = External.curl_easy_setopt_int64(m_pCURL, option, i); } return(retCode); }
public static bool gomultipartpost(string url, string user, string password, string fname, string fpath, int ticketid,int maxwaitsec, bool showprogress, TradeLink.API.DebugDelegate deb, out string result) { debs = deb; Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); Easy easy = new Easy(); rresult = new StringBuilder(); hasresult = false; MultiPartForm mf = new MultiPartForm(); // <input name="frmFileOrigPath"> mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "document[name]", CURLformoption.CURLFORM_COPYCONTENTS, fname, CURLformoption.CURLFORM_END); // <input type="File" name="f1"> mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "document[file]", CURLformoption.CURLFORM_FILE, fpath, CURLformoption.CURLFORM_CONTENTTYPE, "application/octet-stream", CURLformoption.CURLFORM_END); // <input name="frmFileDate"> if (ticketid != 0) mf.AddSection(CURLformoption.CURLFORM_COPYNAME, "document[ticket_id]", CURLformoption.CURLFORM_COPYCONTENTS, ticketid.ToString(), CURLformoption.CURLFORM_END); if (showprogress) { Easy.ProgressFunction pf = new Easy.ProgressFunction(OnProgress); easy.SetOpt(CURLoption.CURLOPT_PROGRESSFUNCTION, pf); } Easy.WriteFunction wf = new Easy.WriteFunction(OnWritePostData); easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf); easy.SetOpt(CURLoption.CURLOPT_HTTPPOST, mf); Easy.DebugFunction df = new Easy.DebugFunction(OnDebug); easy.SetOpt(CURLoption.CURLOPT_DEBUGFUNCTION, df); // simple post - with a string //easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS,data); Slist sl = new Slist(); //sl.Append("Content-Type:multipart/form-data"); sl.Append("Accept: application/xml"); easy.SetOpt(CURLoption.CURLOPT_HTTPHEADER, sl); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, false); easy.SetOpt(CURLoption.CURLOPT_USERAGENT, "Mozilla 4.0 (compatible; MSIE 6.0; Win32"); easy.SetOpt(CURLoption.CURLOPT_FOLLOWLOCATION, true); easy.SetOpt(CURLoption.CURLOPT_USERPWD, user + ":" + password); CURLhttpAuth authflag = CURLhttpAuth.CURLAUTH_BASIC; easy.SetOpt(CURLoption.CURLOPT_HTTPAUTH, authflag); easy.SetOpt(CURLoption.CURLOPT_URL, url); //easy.SetOpt(CURLoption.CURLOPT_POST, true); if (debs != null) easy.SetOpt(CURLoption.CURLOPT_VERBOSE, true); CURLcode err = easy.Perform(); int waits = 0; int maxwaits = 100*maxwaitsec; while (!hasresult && (waits++ < maxwaits)) System.Threading.Thread.Sleep(10); int rcodei = 0; CURLcode rcode = easy.GetInfo(CURLINFO.CURLINFO_RESPONSE_CODE, ref rcodei); if (!hasresult && (deb != null)) deb(easy.StrError(err)); easy.Cleanup(); mf.Free(); Curl.GlobalCleanup(); result = rresult.ToString(); return hasresult && (rcodei==201); }
private bool AddFormFile(LibCurl.MultiPartForm mf, string fileName, Enums.HTMLField field) { return(AddFormFile(mf, fileName, StringEnum.StrVal(field))); }
/// <summary> /// Upload a file to Drupal using the form-file module and CURL /// </summary> /// <param name="localPath">Local file location</param> /// <param name="serverDirectory">Save to a specific directory in drupal</param> /// <returns> File ID or -1 if failed to upload</returns> public int FileUpload(string localPath, string serverDirectory) { // Use file form module string url = ServerURL + "file-form"; LibCurl.MultiPartForm mf = new LibCurl.MultiPartForm(); AddFormFile(mf, localPath, "files[file_upload]"); // Optional parameter - save to a different directory AddFormField(mf, serverDirectory, "file_directory"); AddFormField(mf, "form_token", getToken(url, "edit-file-form-upload-form-token")); AddFormField(mf, "form_id", "file_form_upload"); AddFormField(mf, "op", "Upload file"); EasyCurl.SetOpt(LibCurl.CURLoption.CURLOPT_HTTPPOST, mf); EasyCurl.SetOpt(LibCurl.CURLoption.CURLOPT_URL, url); _htmlDataIn = "";//clear html data in return LibCurl.CURLcode exec = DrupCurlPerform(); // Check if Json returned a file id int fileID; string ex = @"fid"":.""([^""]*)"; Regex rx = new Regex(ex); MatchCollection fields = rx.Matches(_htmlDataIn); if (fields.Count > 0) fileID = Convert.ToInt32(fields[0].Groups[1].Captures[0].Value); else fileID = -1; //JsonUtility.GenerateIndentedJsonText = false; string tempHttp = ""; EasyCurl.GetInfo(LibCurl.CURLINFO.CURLINFO_EFFECTIVE_URL, ref tempHttp); if (((fileID == -1)))// || (tempHttp == ServerURL + "file-form")) { sendLogEvent("Error uploading file, Curl error no: " + "\n", "Curl", Enums.MessageType.Error); } return fileID; }