How to send a photo as parameter
I have a parameter like "currentPhoto" and link API key as http://someapikey.
A user has to choose a photo from photo library and upload it to this link. I need to send this photo as a parameter.
Example:
The user chose a photo to let's name it as myPhoto. I need to send this photo to link http://someapikey as parameter "currentPhoto": myPhoto.
It should post request.
1 answer
-
answered 2017-06-17 19:44
Samiul Islam Sami
You can try this code...
var strBase64: NSString! let image = UIImage(named: "images.jpeg"); let imageData = UIImagePNGRepresentation(image!)! as NSData strBase64 = imageData.base64EncodedString(options: .lineLength64Characters) as NSString let url: String = "http://someapikey" let parameter = ["currentPhoto": strBase64] as [String : Any] Alamofire.request(url, method: .post, parameters: parameter, encoding: JSONEncoding.default) .responseJSON { response in debugPrint(response) }
See also questions close to this topic
-
Pretty Print a JSON string in Rust
I have a String
let str = String::from_utf8(data.to_vec()).unwrap();
How do I pretty-print it with newlines and tabs as JSON?
Essentially I want to do the Rust equivalent of the JavaScript
JSON.stringify(JSON.parse(my_string), null, 4);
This is different than the existing question because I want to parse and then pretty-ify an existing String of JSON, rather than an existing struct.
-
Android - cz.msebera.android.httpclient.entity.ByteArrayEntity required: org.apache.http.HttpEntity
I am using
loopj AsyncHttpClient
to call web services. I am trying register a user. So I need to sendJSON
data to Web Service.ByteArrayEntity entity = new ByteArrayEntity(json.toString().getBytes("UTF-8")); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); client.post(getApplicationContext(), "http://10.0.3.2:8080/WebService/rest/user/insert", entity, new JsonHttpResponseHandler(){
When I put cursor on the
entity
inclient.post
line it gives this error.cz.msebera.android.httpclient.entity.ByteArrayEntity required: org.apache.http.HttpEntity
Example That I am trying is also from stack-overflow - Send JSON as a POST request to server by AsyncHttpClient
Libraries that I am using
compile files('libs/android-async-http-1.4.4.jar') compile 'cz.msebera.android:httpclient:4.3.6'
Anybody can help me? Thanks in advance.
-
Couchbase Lite 2 + JsonConvert
The following code sample writes a simple object to a couchbase lite (version 2) database and reads all objects afterwards. This is what you can find in the official documentation here
This is quite a lot of manual typing since every property of every object must be transferred to the
MutableObject
.class Program { static void Main(string[] args) { Couchbase.Lite.Support.NetDesktop.Activate(); const string DbName = "MyDb"; var db = new Database(DbName); var item = new Item { Name = "test", Value = 5 }; // Serialization HERE var doc = new MutableDocument(); doc.SetString("Name", item.Name); doc.SetInt("Value", item.Value); db.Save(doc); using (var qry = QueryBuilder.Select(SelectResult.All()) .From(DataSource.Database(db))) { foreach (var result in qry.Execute()) { var resultItem = new Item { // Deserialization HERE Name = result[DbName].Dictionary.GetString("Name"), Value = result[DbName].Dictionary.GetInt("Value") }; Console.WriteLine(resultItem.Name); } } Console.ReadKey(); } class Item { public string Name { get; set; } public int Value { get; set; } } }
From my research Couchbase lite uses JsonConvert internally, so there might be a way to simplify all that with the help of JsonConvert.
Anything like:
var json = JsonConvert.SerializeObject(item); var doc = new MutableDocument(json); // No overload to provide raw JSON
or maybe
var data = JsonConvert.SerializeToDict(item); // JsonConvert does not provide this var doc = new MutableDocument(data);
Is there or is this some kind of optimization and the preferred approach is by intend?
-
Laravel $request->all() is empty But $_POST returns the actual posted data in the form correctly
I am facing an issue with Laravel request, Which seems pretty weird to me me. On POST when I check $request->all() it returns an empty array. But $_POST returns the actual posted data in the form correctly.
I am injecting the Request in the method as well.
use Illuminate\Http\Request; public function test(Request $request) { $postedData = $request->all(); return response() ->json($postedData); }
I am also passing the csrf token in the form. I have also tried the questions that are already there on stackoverflow please help me.
My Laravel Version is 5.4
Thanks in advance.
-
Not getting JSON object. AngularJS
I am new in Angular and trying to POST data , but I am getting undefined status. My JSON raw body is like this :
{ "Name": "Something", "Description": "Something", "Data": [] }
Name and description is from user input field and Data will be used later to push another JSON object in the array.
I tried but not getting exact output.
Controller:-
app.controller('postController', ['$scope', '$http', 'appService', function ($scope, $http, AppService) { $scope.addInfos = [{ Name: $scope.name, Description: $scope.description, Data: [] }]; $scope.Create = function () { $scope.addInfos.push({ 'Name': $scope.Name, 'description': $scope.Description, 'Data': [] }); $scope.dataObj = { Name: $scope.name, Description: $scope.description, Data: [] }; $http({ method: 'POST', url: 'http://192.120.27.8:2000/api/Add', data: $scope.dataObj }).then(function (data, status, headers, config) { alert("success"); console.log(data + $scope.Name + $scope.Description); }, function (data, status, headers, config) { alert("error"); }); $scope.name = ''; $scope.Description = ''; };
HTML page :-
<div class="input-group col-md-10"> <span class="input-group-addon" id="reg_input" >Name</span> <input type="text" class="form-control" placeholder="" ng-model="addInfos.name"> </div> <div class="input-group sepH_b col-md-10"> <span class="input-group-addon" id="reg_input" >Description</span> <textarea name="reg_textarea" id="reg_textarea" cols="10" rows="3" class="form-control" ng-model="addInfos.description"></textarea> </div> <div class="col-md-4"> <a style="" class="btn btn-md btn-primary" ng-click="Create(addInfos)">Create</a> </div>
The output which I can see in my console is
[object Object]
. What mistake am I doing here ? NOTE:- Here I didn't mentioned Data: field as it will be predefined array as of now like this{data:[]}
need to inject and pass Name and Description in JSON as I mentioned above.SECOND also I need to push this over all output data to the Service to store for further use.
-
Send a lot of async REST requests
I'd like to create a Java-based application which will send 2,000,000 (or more) async REST requests one by one to the server, and wait for all futures.
1) I'm using the Apache HTTP client:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5</version> </dependency>
2) My connection manager looks like this:
public static PoolingHttpClientConnectionManager getConnectionManager() { Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory> create() .register("http", new PlainConnectionSocketFactory()) .build(); PoolingHttpClientConnectionManager cm = (socketFactoryRegistry != null) ? new PoolingHttpClientConnectionManager(socketFactoryRegistry): new PoolingHttpClientConnectionManager(); // twitter specific options cm.setMaxTotal(2000); cm.setDefaultMaxPerRoute(200); return cm; }
3) My async execution looks like this:
ExecutorService executor = Executors.newFixedThreadPool(THREADS_COUNT); Orders.getInstance().generateOrders(); long startTime = System.currentTimeMillis(); executor.invokeAll(... 2 millions of Request ); executor.shutdown(); executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
4) My callable (request) looks like this:
public class Request implements Callable<Response> { private PoolingHttpClientConnectionManager manager; private String url; private Order order; public Request(PoolingHttpClientConnectionManager manager, String url, Order order) { this.manager = manager; this.url = url; this.order = order; } @Override public Response call() { CloseableHttpClient client = HttpClients.custom().setConnectionManager(manager) .build(); HttpPost post = createRequest(); try { return new Response(client.execute(post)); } catch (IOException e) { e.printStackTrace(); return null; } finally { //client.getConnectionManager().shutdown(); } } private HttpPost createRequest() { HttpPost postRequest = new HttpPost(url); StringEntity input = null; try { input = new StringEntity(order.toJson()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } input.setContentType("application/json"); postRequest.setEntity(input); return postRequest; } }
Currently the client is just stopping on
invokeAll
with no reason or exception thrown.Maybe somebody has ideas what might be wrong? Or maybe just a different solution?
-
Can't get product info retrieveProductsInfo in Swift3
I use SwiftyStoreKit can't get purchase info retrieveproductsinfo.. I don't know why don't get
AppDelegate.swift
SwiftyStoreKit.completeTransactions(atomically: true) { purchases in for purchase in purchases { switch purchase.transaction.transactionState { case .purchased, .restored: if purchase.needsFinishTransaction { // Deliver content from server, then: SwiftyStoreKit.finishTransaction(purchase.transaction) } // Unlock content case .failed, .purchasing, .deferred: break // do nothing } } }
ControllerView.swift
SwiftyStoreKit.retrieveProductsInfo(["1000_dal_point"]){ result in print("result : \(result)") if let product = result.retrievedProducts.first { let priceString = product.localizedPrice! print("Product : \(product.localizedDescription), Price: \(priceString)") }else if let invalidProductId = result.invalidProductIDs.first { return self.showErrorAlert(title: "Itunes error", error: "productId \(invalidProductId)") }else { print("Error: \(String(describing: result.error))") } }
I used breakpoint in appdelegate it does not even enter into purchases in ~. how about this?
-
Login to server with iOS app
I'm trying to create an app that logs in to a server with username and password and receives JSON object. In my browser, I just click the link, I put in username and password and I can see all data I need, but I am not able to pull this off with an app. There is not much about this on the internet.
This code does not work, neither does standard GET request (I guess I cannot include any username or password with that). Thank you very much for any piece of advice.
let url = URL(string: "https://api.comproportal.com/v4/monthlyGraph.php?compressor_id=15&day=19.2.2018") let request = NSMutableURLRequest(url: url!) request.httpMethod = "POST" let toSend = "form-username=" + user + "&form-password=" + psw print("toSend: \(toSend)") // URL Encoding let encodedString = toSend.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) print(encodedString!) // server is expecting utf8 encoding right? request.httpBody = escapedString?.data(using: String.Encoding.utf8) print(request.httpBody) let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in guard let _:Data = data else { return } let json:Any? do { json = try JSONSerialization.jsonObject(with: data!, options: []) print(json) } catch { return } guard let server_response = json as? NSDictionary else { return } print(server_response) } task.resume()
-
Sharing Data between App Groups not working on real device instead working on simulator
Hello I'm working on something where I need to pass some data from a target to another (basically an app to another) and I red that App Groups is the way to do it .
I've made a class to manage that .class PaywallHelper { static let sharedDefaults = UserDefaults.init(suiteName: "group.Myapp")! var tokenForPaywall: String? { get { return PaywallHelper.sharedDefaults.string(forKey: "user_token") } set { PaywallHelper.sharedDefaults.setValue(newValue, forKey: "user_token") PaywallHelper.sharedDefaults.synchronize() } } var ad_id: Int? { get { return PaywallHelper.sharedDefaults.integer(forKey: "id") } set { PaywallHelper.sharedDefaults.setValue(newValue, forKey: "id") PaywallHelper.sharedDefaults.synchronize() } } var category_id: Int? { get { return PaywallHelper.sharedDefaults.integer(forKey: "category_id") } set { PaywallHelper.sharedDefaults.setValue(newValue, forKey: "category_id") PaywallHelper.sharedDefaults.synchronize() } }
also I have enabled the App Groups from Capabilities ...but what botheres me here is that it is red... ..
The thing is it is working fine on simulator I receive the data and i can work with them...as for the real device it s not working...What am I doing wrong?
-
Crash while uploading image using Alamofire
I'm uploading an image using Alamofire like so..
EDIT: This is the edited code...
for img in images { let url = "http:my url" let headers = [ "Accept": "application/json", "Authorization": self.accessToken ] if let imageData = (UIImageJPEGRepresentation(img, 0.6)) { let parameters: [String: String] = [ "seller_id": "\(self.mySellerId)", "offline_id": self.prodID, "is_default": "1", "sequence": "\(sequenceCount)" ] Alamofire.upload(multipartFormData: {(multipartFormData) in let filePath = NSURL(fileURLWithPath: url) print(imageData) multipartFormData.append (imageData, withName: "image", fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: "image / jpg") for (key, value ) in parameters { print(key,value) multipartFormData.append(value.data(using: .utf8)!, withName: key) } }, to: url, method: .post, headers: headers) { (result) in switch result { case .success(let upload, _,_ ): upload.uploadProgress(closure: { (progress) in UILabel().text = "\((progress.fractionCompleted * 100)) %" print (progress.fractionCompleted * 100) }) upload.responseJSON { response in if let JSON = response.result.value { print(JSON) }else{ print("Error") } } case .failure(let encodingError): print(encodingError) break } } } }
In the part
for (key, value) in parameters...
the for loop goes through all values. But when it reaches the image data part, it crashes sayingCould not cast value of type 'Foundation.Data' (0x10787b9f0) to 'Swift.String'
What should be given instead so that the error can be fixed..?
-
Error in closure tuple parameter
I'm trying to write an API layer using RxSwift and RxAlamofire. Here is the code for API request.
public func _request(_ method: Alamofire.HTTPMethod, url: URLConvertible, parameters: [String : Any]? , encoding: ParameterEncoding, headers: [String : String]?, isSecondTryAfterAuth: Bool = false) -> RxSwift.Observable<(HTTPURLResponse, Any)> { return RxAlamofire .requestJSON(method, url, parameters: parameters, encoding: JSONEncoding.default, headers: self.appDelegateInstance.refreshToken) .map({ (response, json) -> Observable<(HTTPURLResponse, Any)> in return Observable.just(response, json) }) }
I got an error in .map function "Closure tuple parameter '(HTTPURLResponse, Any)' does not support destructuring". Any idea about how to solve this?
-
send array of json objects in ios
I have a post request that has a body like this
{ "cars": [ { "id": 126, "drivers": [ "xxx@gmail.com" ] }, { "id": 128, "drivers": [ "mmm@gmail.com" ] } ] }
the id and drivers are changeable, and I got them from another api so how to send this body with the post request?
on the other hand I have a textField that takes another email of driver, I want to change drivers when this request was sent.
example:
{ "cars": [ { "id": 126, "drivers": [ "xxx@gmail.com", "sss@gmail.com" ] }, { "id": 128, "drivers": [ "mmm@gmail.com" ] } ] }
As you can see I want to update the drivers to the new one when I tap add button on the specific
textField
depends on the id.This is my code
public static func loadDrivers(owners: [Owner], drivers: [Driver], driverEmail: String!, i: Int, completion: @escaping (_ code:Int?)-> Void) { let headers: HTTPHeaders = [ "Accept": "application/json" ] var para2 = [String : [[String : Any]]]() para2 = [ "cars": [ [ "id": owners[i].id, "drivers": [ drivers[i].email, driverEmail ] ] ] ] if driverEmail != nil { Alamofire.request(APIHelper.BASE_URL + APIHelper.API.ADD_DRIVERS.rawValue, method: .post, parameters: para2, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in switch response.result { case .success: let json = response.result.value as? NSDictionary let code = json!["code"] completion(code as? Int) case .failure(let error): print(error) completion(nil) return } } } }
Thanks in advance
-
How to send email with not necessary Multiple Attachments from html form in PHP
I have get value from html form and send via email with multiple attachments. Attachments are not necessary.
I have got some piece of code to send multiple attachments through mail function in php But my mail sending fails and i dont know why. My attachments are not necessary. This is my code:
<?php function multi_attach_mail($to, $subject, $message, $senderMail, $senderName, $files){ $from = $senderName." <".$senderMail.">"; $headers = "Siuntėjęs: $from"; // boundary $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; // headers for attachment $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // multipart boundary $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"utf-8\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; // preparing attachments if(count($files) > 0){ for($i=0;$i<count($files);$i++){ if(is_file($files[$i])){ $message .= "--{$mime_boundary}\n"; $fp = @fopen($files[$i],"rb"); $data = @fread($fp,filesize($files[$i])); @fclose($fp); $data = chunk_split(base64_encode($data)); $message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" . "Content-Description: ".basename($files[$i])."\n" . "Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; } } } $message .= "--{$mime_boundary}--"; $returnpath = "-f" . $senderMail; //send email $mail = @mail($to, $subject, $message, $headers, $returnpath); //function return true, if email sent, otherwise return fasle if($mail){ return TRUE; } else { return FALSE; } } if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['namecontact']) && !empty($_POST['namecarinfo']) ) { $contacts = array( //"autoperka.info@gmail.com", //"automobiliukas24@gmail.com", // "ruslanneviadomskij@gmail.com", "gabriele.giniot@gmail.com" ); foreach($contacts as $contact) { $to = $contact; // this is your Email address $from = $_POST['namecontact']; // this is the sender's Email address $carinformation = $_POST['namecarinfo']; $coment = $_POST['namecoment']; $subject = $from . " SupirkimasPlius.lt"; $from_name = $_POST['namecontact']; //$headers = "Siuntėjas:" . $from; //attachment files path array $file_tmp_name = $_FILES['namephoto']['tmp_name']; $fileName = $_FILES['namephoto']['name']; $fileType = $_FILES['namephoto']['type']; $files = $fileType; // Message $html_content = '<br> <h3>Automobilio pasiūlymas:</h3> <br>Marke: '.$carinformation.' <br>Kontaktai: '.$from.' <br>Komentaras: '.$coment. '<br>Nuotraukų kiekis'.count($files); //call multi_attach_mail() function and pass the required arguments $send_email = multi_attach_mail($to,$subject,$html_content,$from,$from_name,$files); //print message after email sent } $myfile = fopen("success.php", "r") or die(fopen("index.php", "r")); echo fread($myfile,filesize("success.php")); fclose($myfile); //mail('gabriele.giniot@gmail.com',$subject,$message,$headers); //mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender } else { $myfile = fopen("failed.php", "r") or die(fopen("index.php", "r")); echo fread($myfile,filesize("failed.php")); fclose($myfile); } ?>
please help me :)
-
Zapier - Post Instagram photo and caption in a specific Facebook album
Anyone know how to do this? Maybe the middle zap needs to be a special code?
-
Can't paste .mov file to external hard drive
I'm trying to transfer all my pictures and little .mov files to my external hd. I've formatted the hard disk to exfat which should work with apple's mov format and windows. all the jpeg transferred nicely but not the mov. Why? and How do I fix that? Do I have to reformat to HFS?
Thank you in advance
Didi