Upload image array and parameters to server using alamofire - swift

I am trying to upload a group of few images (image array) and parameters to server with the help of Alamofire library. The problem is I want to upload images with same id but with different name and I am getting completely opposite to this. I have also referred with some questions which are answered on stack overflow but those are for single image upload. Please help friends. Thanks in advance.
Upload Function
let parameters = [
"defect_id" : "10",
"file_name" : self.dateMashup(1)
]
Alamofire.upload(
multipartFormData: { multipartFormData in
var count = 1
for img in self.photoArray{
let imgdata = UIImagePNGRepresentation(img)
// the name should be as array other wise want work
let randsome = self.dateMashup(count)
multipartFormData.append(imgdata!,withName: "image[]", fileName: "image\(randsome).png", mimeType: "image/png")
count += 1
}
for (key, value) in parameters {
multipartFormData.append(value.data(using: .utf8)!, withName: key)
}
},
to: "http://localhost/Source2/ImageDir/uploadImages.php",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseString { response in
debugPrint(response)
}
case .failure(let encodingError):
print(encodingError)
}
})
PHP file
<?php
$server = "localhost";
$dbuser = "root";
$dbpassword = "";
$dbname = "lmg_new";
$con = mysqli_connect($server, $dbuser, $dbpassword, $dbname);
$defect_id=$_POST["defect_id"];
$file_name = $_POST["file_name"];
$created = date('Y-m-d H:i:s');
// $defect_id = 1;
// $file_name = "sadas.png";
// $created = date('Y-m-d H:i:s');
$sql = "INSERT INTO `files`(`defect_id`, `file_name`, `created`) VALUES (defect_id, file_name, created)";
$result= mysqli_query($con, $sql) or die("query fail:". mysqli_error($con));
// $response = array();
$response["success"]= true;
if($result){
while($row = mysqli_fetch_assoc($result))
{
$flag[]=$row;
}
$response['data'] = $flag;
}
if (empty($_FILES["image"])){
$response['File1'] = "NOFILE";
}else{
foreach ($_FILES["image"]["tmp_name"] as $index => $tmp_name) {
$filePath = "images/" . basename($_FILES["image"]["name"][$index]);
if (move_uploaded_file($tmp_name, $filePath)) {
$response['filePath'][$index] = $filePath;
}
$response['status'] = "Success";
}
}
echo json_encode($response);
?>

Related

make a custom error message and prevent duplicate mail id from inserting in db

I have checked email unique in codeigniter. In else past I diplayed error. But the system error is not convenient. how to customise error...
i have tried giveng javascript alert instead of that error message... but after that alert the data are storing in database.. Actually the data should not store in database if the email is not unique..
public function add_applicants() {
// $field_name=$this->input->post('photo');
$data = $this->input->post();
$mobile = $this->db->get_where('applicants',array('mobile_number'=>$this->input->post('mobile_number')));
if($mobile->num_rows()>0)
{
throw new Exception("Mobile Number Already Registered");
}
$email = $this->db->get_where('applicants',array('email_id'=>$this->input->post('email_id')));
if($email->num_rows()>0)
{
throw new Exception("Email_id Already Registered");
}
$school_id= $this->input->post('school_code');
$name_of_exam= $this->input->post('name_of_exam');
$name= $this->input->post('name_candiadte');
switch($name_of_exam){
case '1':
$exam='NMMS';
break;
case '2':
$exam='NTS';
break;
}
$school_code = $this->Welcome_Model->getschoolData($school_id);
if (isset($_FILES['photo']) == 1) {
$config['upload_path'] = FCPATH . 'uploads/'. $school_code->name_of_the_school.'/'. $exam ;
$this->upload_path = $config['upload_path'];
if ($this->validate_upload_path() == TRUE) {
$config['upload_path'] = $this->upload_path;
// print_r($this->upload_path) ;
// die();
}
$config['allowed_types'] = 'jpg';
$config['max_size'] = 2000;
$config['remove_spaces'] = TRUE;
$config['overwrite'] = true;
$config['file_name'] = $name.'-'.date('Ymdhis') . '.jpg';
$file_name = $config['file_name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('photo')) {
$this->upload->display_errors();
}
}
$data['photo'] = $file_name;
$insetapplicants = $this->Welcome_Model->insertApplicants($data);
if ($insetapplicants == 'Success') {
echo "<script>
alert('New Applicants Added Successfully');
// window.location.href='dashboard';
</script>";
}
}

How to post Integer in Alamofire Parameters

i followed a tutorial for Register and Login Request in xcode.
But i have a problem with the Code because i changed some values of it.
My variables in the php script are ssiss (string, string, int, string, string). In the swift file i am using Alamofire. Here it is:
#IBAction func buttonRegister(_ sender: UIButton) {
let ageINT = Int(ageTF.text!);
//creating parameters for the post request
let parameters: Parameters=[
"name":nameTF.text!,
"username":usernameTF.text!,
"age": ageINT ?? 0,
"country":countryTF.text!,
"password":passwordTF.text!,
]
//Sending http post request
Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON
{
response in
//printing response
print(response)
//getting the json value from the server
if let result = response.result.value {
//converting it as NSDictionary
let jsonData = result as! NSDictionary
//displaying the message in label
self.labelMessage.text = jsonData.value(forKey: "message") as! String?
}
}
I think the problem is i pass an String value instead of a integer value. That is why i already have changed the value for "age" from "age":ageTF.text!, to "age": ageINT ?? 0,
The error i am get is "Required parameters are missing".
I am getting this "error-response" message because of this php-script:
<?php
//importing required script
require_once '../includes/DbOperation.php';
$response = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!verifyRequiredParams(array('name', 'username', 'age', 'country', 'password'))) {
//getting values
$name = $_POST["name"];
$username = $_POST["username"];
$age = $_POST["age"];
$country = $_POST["country"];
$password = $_POST["password"];
//creating db operation object
$db = new DbOperation();
//adding user to database
$result = $db->createUser($name, $username, $age, $country, $password);
//making the response accordingly
if ($result == USER_CREATED) {
$response['error'] = false;
$response['message'] = 'User created successfully';
} elseif ($result == USER_ALREADY_EXIST) {
$response['error'] = true;
$response['message'] = 'User already exist';
} elseif ($result == USER_NOT_CREATED) {
$response['error'] = true;
$response['message'] = 'Some error occurred';
}
} else {
$response['error'] = true;
$response['message'] = 'Required parameters are missing';
}
} else {
$response['error'] = true;
$response['message'] = 'Invalid request';
}
//function to validate the required parameter in request
function verifyRequiredParams($required_fields)
{
//Getting the request parameters
$request_params = $_REQUEST;
//Looping through all the parameters
foreach ($required_fields as $field) {
//if any requred parameter is missing
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
//returning true;
return true;
}
}
return false;
}
print_r(json_encode($response));
?>
And this is the other php script:
<?php
class DbOperation
{
private $conn;
//Constructor
function __construct()
{
require_once dirname(__FILE__) . '/Constants.php';
require_once dirname(__FILE__) . '/DbConnect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
//Function to create a new user
public function createUser($name, $username, $age, $country, $password)
{
if (!$this->isUserExist($username)) {
$password = md5($pass);
$stmt = $this->conn->prepare("INSERT INTO user (name, username, age, country, password) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("ssiss", $name, $username, $age, $country, $password);
if ($stmt->execute()) {
return USER_CREATED;
} else {
return USER_NOT_CREATED;
}
} else {
return USER_ALREADY_EXIST;
}
}
private function isUserExist($username)
{
$stmt = $this->conn->prepare("SELECT id FROM user WHERE username = ? ");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
return $stmt->num_rows > 0;
}
}

RESTful uploading of a video file in PHP

I want to upload a video file to a server using POST request. There is not much information available about it in the internet.
I usually do check the data what i have send using this code
$params = $_REQUEST;
return $params;
I check it in POSTMAN. I have table called video_review
id
video_url
movie_id
user_id
date_time
when i choose a video file and click send i want the location of video file to be saved into the video_url field. But in the controller when i run this code return $params; i get nothing.
EDIT
Made some progress
public function actionCreate_video_review()
{
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma","mkv");
$extension = pathinfo($_FILES['video_url']['name'], PATHINFO_EXTENSION);
if ( ($_FILES["video_url"]["type"] == "video/mp4")|| ($_FILES["video_url"]["type"] == "video/x-matroska")
&& ($_FILES["video_url"]["size"] < 20000)
&& in_array($extension, $allowedExts) )
{
if ($_FILES["video_url"]["error"] > 0)
{
return $_FILES["video_url"]["error"];
}
else
{
if (file_exists("upload/" . $_FILES["video_url"]["name"]))
{
echo $_FILES["video_url"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["video_url"]["tmp_name"],
"upload/" . $_FILES["video_url"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["video_url"]["name"];
return $_FILES["video_url"]["name"];
}
}}
i got it working.
//POST Video Reviews
public function actionCreate_video_review()
{
$allowedExts = array("jpg", "jpeg", "gif", "png", "mp3", "mp4", "wma","mkv");
$extension = pathinfo($_FILES['video_url']['name'], PATHINFO_EXTENSION);
if ( ($_FILES["video_url"]["type"] == "video/mp4")|| ($_FILES["video_url"]["type"] == "video/x-matroska")&& ($_FILES["video_url"]["size"] < 90000) && in_array($extension, $allowedExts) )
{
if ($_FILES["video_url"]["error"] > 0)
{
return $_FILES["video_url"]["error"];
}
else
{
if (file_exists("upload/" . $_FILES["video_url"]["name"]))
{
echo $_FILES["video_url"]["name"] . " already exists. ";
}
else
{
$model = new \app\models\VideoReview();
$model->video_url = $_FILES["video_url"]["name"];
$model->save();
move_uploaded_file($_FILES["video_url"]["tmp_name"],
\Yii::$app->basePath. '/web/uploads/' . $_FILES["video_url"]["name"]);
return $_FILES["video_url"]["name"];
}
}
}
else
{
return $_FILES["video_url"]["error"] ."Error";
}
}

EnvelopeID Changed after correction?

I have 2 signature document and the first signer already signed. The document is still in process. So I went to correct the second signer. I realised the envelopeID changed after the correction.
What will it happen to the old envelope? Voided?
function getDocuments($pdfbytes) {
$documents = array();
$id = 1;
$d = new Document();
$d->PDFBytes = $pdfbytes;
$d->Name = "Demo Document";
$d->ID = $id++;;
$d->FileExtension = "pdf";
array_push($documents, $d);
return $documents;
}
function buildEnvelope($pdfbytes) {
$envelope = new Envelope();
$envelope->Subject = $_SESSION["Taskmaster"];
$envelope->EmailBlurb = "Please Sign by logining ";
$envelope->AccountId = $_SESSION["AccountID"];
$envelope->Recipients = constructRecipients();
$envelope->Tabs = addTabs(count($envelope->Recipients));
$envelope = processOptions($envelope);
$envelope->Documents = getDocuments($pdfbytes);
return $envelope;
}
function constructRecipients() {
$recipients = array();
$r = new Recipient();
$r->UserName =$_SESSION["Secretaryname"];
$r->Email = $_SESSION["Secretaryemail"];
$r->RequireIDLookup = false;
$r->ID = 1;
$r->Type = RecipientTypeCode::Signer;
$r->RoutingOrder = "2";
// if(!isset($_POST['RecipientInviteToggle'][$i])){
$r->CaptiveInfo = new RecipientCaptiveInfo();
$r->CaptiveInfo->ClientUserId = 2;
$r->CaptiveInfo->embeddedRecipientStartURL=SIGN_AT_DOCUSIGN;
// }
array_push($recipients, $r);
if(empty($recipients)){
$_SESSION["errorMessage"] = "You must include at least 1 Recipient";
//header("Location: error.php");
exit;
}
return $recipients;
}
function sendNow($envelope) {
$api = getAPI();
$csParams = new CreateAndSendEnvelope();
$csParams->Envelope = $envelope;
//print_r($csParams);
try {
$status = $api->CreateAndSendEnvelope($csParams)->CreateAndSendEnvelopeResult;
//echo "Result for Create and Send <br>";
//print_r($status);
if ($status->Status == EnvelopeStatusCode::Sent) {
addEnvelopeID($status->EnvelopeID);
$correct = new Correction;
$correct->EnvelopeID = $status->EnvelopeID;
$correct->RecipientCorrections = addRecipientCorrection();
$correctparams = new CorrectAndResendEnvelope();
$correctparams->Correction = $correct;
//print_r($correctparams);
//Send
$response = $api->CorrectAndResendEnvelope($correctparams);
//print_r($response);
//exit;
$_SESSION["EnvelopeID"]=null;
$_SESSION["Direct"]="Yes";
header("Location: getstatusanddocs.php?envelopid=" . $status->EnvelopeID .
"&accountID=" . $envelope->AccountId . "&source=Document");
}
} catch (SoapFault $e) {
$_SESSION["errorMessage"] = $e;
header("Location: error.php");
}
}
function addRecipientCorrection(){
$correction = new RecipientCorrection();
$correction->PreviousUserName = "xxxxxx";
$correction->PreviousEmail = "xxxxxxx";
$correction->PreviousSignerName = $correction->PreviousUserName;
$correction->PreviousRoutingOrder = "2";
$correction->CorrectedUserName = $_SESSION["Secretaryname"];
$correction->CorrectedEmail = $_SESSION["Secretaryemail"];
$correction->CorrectedSignerName = $correction->CorrectedUserName;
return $correction;
}
//========================================================================
// Main
//========================================================================
loginCheck();
if($_SESSION["Taskmaster"]=="xxxxx"){
$api = getAPI();
$RequestPDFParam = new RequestPDF();
$RequestPDFParam->EnvelopeID = $_SESSION["EnvelopeID"];
$result = $api->RequestPDF($RequestPDFParam);
$envPDF = $result->RequestPDFResult;
//file_put_contents("./Cert/".$_SESSION["EnvelopeID"].".pdf", $envPDF->PDFBytes);
//echo "Stop here";
//exit;
$envelope = buildEnvelope($envPDF->PDFBytes);
sendNow($envelope);
}else{
echo "You have no power";
}
EnvelopeId does not change after correction. The envelopeID never changes. New envelopes can be created, but the original GUID that was used will keep living in the system.

How to get my zend script picture filename into a hidden field

OK, I am stumped here. I'm using a Zend script that helps me to upload pictures. It works great, but I am trying to capture the pictures name into a hidden field for a form. I'd like to note that the name changes, so I'd need to get whichever it ends up being put into the hidden field. Here is the Zend script:
<?php
if (isset($_POST['upload'])) {
require_once('scripts/library.php');
try {
$destination = 'xxxxxxxx';
$uploader = new Zend_File_Transfer_Adapter_Http();
$uploader->setDestination($destination);
$filename = $uploader->getFileName(NULL, FALSE);
$uploader->addValidator('Size', FALSE, '90kB');
$uploader->addValidator('ImageSize', FALSE, array('minheight' => 100, 'minwidth' => 100));
if (!$uploader->isValid()) {
$messages = $uploader->getMessages();
} else {
$no_spaces = str_replace(' ', '_', $filename, $renamed);
$uploader->addValidator('Extension', FALSE, 'gif, png, jpg');
$recognized = FALSE;
if ($uploader->isValid()) {
$recognized = TRUE;
} else {
$mime = $uploader->getMimeType();
$acceptable = array('jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$key = array_search($mime, $acceptable);
if (!$key) {
$messages[] = 'Unrecognized image type';
} else {
$no_spaces = "$no_spaces.$key";
$recognized = TRUE;
$renamed = TRUE;
}
}
$uploader->clearValidators();
if ($recognized) {
$existing = scandir($destination);
if (in_array($no_spaces, $existing)) {
$dot = strrpos($no_spaces, '.');
$base = substr($no_spaces, 0, $dot);
$extension = substr($no_spaces, $dot);
$i = 1;
do {
$no_spaces = $base . '_' . $i++ . $extension;
} while (in_array($no_spaces, $existing));
$renamed = TRUE;
}
$uploader->addFilter('Rename', array('target' => $no_spaces));
$success = $uploader->receive();
if (!$success) {
$messages = $uploader->getMessages();
} else {
$uploaded = "$filename uploaded successfully";
$pic = $filename;
if ($renamed) {
$uploaded .= " and renamed $no_spaces";
}
$messages[] = "$uploaded";
}
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
Here I am trying to make the $pic variable not to throw an error for now (on the form page)
if (isset($_POST['upload'])) { } else { $pic = "unknown";}
The $pic variable is what I was trying to have the filename from the zend script copied into. Any feedback is greaaaatly appreciated :)