/// <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); }
private string getToken(string url, string formId) { _htmlDataIn = ""; //clear data in string EasyCurl.SetOpt(LibCurl.CURLoption.CURLOPT_URL, url); LibCurl.CURLcode exec = DrupCurlPerform(); if (HttpConnectCode != 200) { sendLogEvent("Error access " + HttpConnectCode.ToString() + "\n", "Curl", Enums.MessageType.Error); _htmlDataIn = ""; return(""); } Regex rx = new Regex(formId + @".*value=""([^""]*)"); MatchCollection fields = rx.Matches(_htmlDataIn); _htmlDataIn = ""; if (fields.Count > 0) { return(fields[0].Groups[1].Captures[0].Value); } else { return(""); } }