Rectangle 27 7

Sorry, this is unclear in my previous question. The whole request body is multipart/form-data. I am asking specifically about the specific parameter containing the file data.

The encoding specification doesn't tell anything about the need to encode the parts as Base64, so the answer is still no. It would only make it unnecessarily complicated and incompatible with existing multipart/form-data parsers because they don't expect the values been encoded in Base64 and you thus need to decode them yourself afterwards.

Should a HTTP POST'ed file be base64 encoded? - Stack Overflow

http base64
Rectangle 27 1

How to create a VCF 3.0 card for iOS/macOS

VCARD > PHOTO - An image or photograph of the individual associated with the vCard. It may point to an external URL or may be embedded in the vCard as a Base64 encoded block of text.

2.1: PHOTO;JPEG:http://example.com/photo.jpg
2.1: PHOTO;JPEG;ENCODING=BASE64:[base64-data]
3.0: PHOTO;TYPE=JPEG;VALUE=URI:http://example.com/photo.jpg
=> 3.0: PHOTO;TYPE=JPEG;ENCODING=b:[base64-data]             // Works in iOS/macOS
4.0: PHOTO;MEDIATYPE=image/jpeg:http://example.com/photo.jpg
4.0: PHOTO:data:image/jpeg;base64,[base64-data]

Testing shows the 2nd way works: encode the JPEG photo using base64.

PHOTO;ENCODING=b;TYPE=JPEG:\(base64EncodedImage)
struct VCFBuilder {
    private let name: String? = "Name1"
    private let company: String? = "Company"
    private let title: String? = "Title1"
    private let phone: String? = "555-1234-1234"
    private let address: String? = "aaa"
    private let notes: String? = "PROnotes"
    private let web: String? = "web"
    private let blog: String? = "bolgg"
    private let socialMedia1: String? = "social1"
    private let socialMedia2: String? = "social2"
    private let socialMedia3: String? = "social3"
    private let email: String? = "email@mail.com"
    private let imageUrl: String? = "http://0.gravatar.com/avatar/3f009d72559f51e7e454b16e5d0687a1"

    func vcf() -> String? {

        do {
            let url = URL(string: self.imageUrl!)
            let data = try Data(contentsOf: url!).base64EncodedString()
            return generateVCF(withEncodedImage: data)
        } catch {
            print(error)
            return nil
        }
    }

    // TODO: Don't !
    private func generateVCF(withEncodedImage imageBase64: String) -> String {
        return """
        BEGIN:VCARD
        VERSION:3.0
        N:\(self.name!);
        FN:\(self.name!)
        ORG:\(self.company!)
        TITLE:\(self.title!)
        TEL;TYPE=WORK,VOICE:\(self.phone!)
        ADR;TYPE=WORK:;;\(self.address!)
        NOTE:\(self.notes!)
        PHOTO;ENCODING=b;TYPE=JPEG:\(imageBase64)
        item1.URL:\(self.web!)
        item2.URL:\(self.blog!)
        item3.URL:\(self.socialMedia1!)
        item4.URL:\(self.socialMedia2!)
        item5.URL:\(self.socialMedia3!)
        EMAIL;TYPE=PREF,INTERNET:\(self.email!)
        END:VCARD
        """
    }
}

let vcf = VCFBuilder().vcf()
print(vcf)
ABPersonCreatePeopleInSourceWithVCardRepresentation(_:_:)
CNContactVCardSerialization.contacts(with:)
guard let data = VCFBuilder().vcf()?.data(using: .utf8),
      let contact = try? CNContactVCardSerialization.contacts(with: data).first
        else { return }

print(contact.imageData!.base64EncodedString())

So i have to covert image data to base64 string and append it to the vCard? Will it then also import picture to contacts when imported?

Yes, you need to append the base64 encoded image as shown in the poc code

@SalmanAli works as excepted. Image MUST be a JPEG. See attached image

ios - Export Picture in VCard Swift - Stack Overflow

ios swift xcode vcard
Rectangle 27 7

if you want to upload an image as a string you must convert your image data to Base64, then you can use your above method:-

You can directly upload an image like so:

-(void)uploadImage
{       
    NSData *imageData = UIImagePNGRepresentation(yourImage);

    NSString *urlString = [ NSString stringWithFormat:@"http://yourUploadImageURl.php?intid=%@",1];

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", 1]] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];

    [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}

iphone - How to upload image to server from gallery as JSON on iOS - S...

iphone ios json
Rectangle 27 27

It's only useful for very tiny images. Base64 encoded files are larger than the original. The advantage lies in not having to open another connection and make a HTTP request to the server for the image. This benefit is lost very quickly so there's only an advantage for large numbers of very tiny individual images.

Some enterprise CMS (like RedDot) also need CSS images to be "hooked up" - a 4 click process. Depending on your platform it could be a time saver.

html - Advantages and disadvantages of using base64 encoded images - S...

html css image base64 encode
Rectangle 27 26

It's only useful for very tiny images. Base64 encoded files are larger than the original. The advantage lies in not having to open another connection and make a HTTP request to the server for the image. This benefit is lost very quickly so there's only an advantage for large numbers of very tiny individual images.

Some enterprise CMS (like RedDot) also need CSS images to be "hooked up" - a 4 click process. Depending on your platform it could be a time saver.

html - Advantages and disadvantages of using base64 encoded images - S...

html css image base64 encode
Rectangle 27 25

It's only useful for very tiny images. Base64 encoded files are larger than the original. The advantage lies in not having to open another connection and make a HTTP request to the server for the image. This benefit is lost very quickly so there's only an advantage for large numbers of very tiny individual images.

Some enterprise CMS (like RedDot) also need CSS images to be "hooked up" - a 4 click process. Depending on your platform it could be a time saver.

html - advantages and disadvantages base64 image encode - Stack Overfl...

html css image base64 encode
Rectangle 27 2

This link may prove interesting. Basically he state that Base64 encoded data is 33% larger and takes longer to process than binary.

htmltrocks has an interesting article regarding integrating the canvas element into your App. It shows use of the HTML5 canvas toDataURL() method which converts to Base64.

The 33% increase should be taken with a pinch of salt. If you have a website that uses gzip compression the overhead drops to 9%. Plus if that data can be inlined it saves additional requests. The other interesting thing is that Base64 is claimed that it may be slower. Its important to realise that often the quickest development solution is the best, developer time is more valuable than a few ms in most cases.

angularjs - Angular Base64 file upload as JSON - Stack Overflow

json angularjs file-upload base64
Rectangle 27 12

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;


public class MainActivity extends Activity {

    Button btpic, btnup;
    private Uri fileUri;
    String picturePath;
    Uri selectedImage;
    Bitmap photo;
    String ba1;
    public static String URL = "Paste your URL here";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btpic = (Button) findViewById(R.id.cpic);
        btpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickpic();
            }
        });

        btnup = (Button) findViewById(R.id.up);
        btnup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upload();
            }
        });
    }

    private void upload() {
        // Image location URL
        Log.e("path", "----------------" + picturePath);

        // Image
        Bitmap bm = BitmapFactory.decodeFile(picturePath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
       //ba1 = Base64.encodeBytes(ba);

        Log.e("base64", "-----" + ba1);

        // Upload image to server
        new uploadToServer().execute();

    }

    private void clickpic() {
        // Check Camera
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // Open default camera
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            // start the image capture Intent
            startActivityForResult(intent, 100);

        } else {
            Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {

            selectedImage = data.getData();
            photo = (Bitmap) data.getExtras().get("data");

            // Cursor to get image uri to display

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            Bitmap photo = (Bitmap) data.getExtras().get("data");
            ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
            imageView.setImageBitmap(photo);
        }
    }

    public class uploadToServer extends AsyncTask<Void, Void, String> {

        private ProgressDialog pd = new ProgressDialog(MainActivity.this);
        protected void onPreExecute() {
            super.onPreExecute();
            pd.setMessage("Wait image uploading!");
            pd.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("base64", ba1));
            nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(URL);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                String st = EntityUtils.toString(response.getEntity());
                Log.v("log_tag", "In the try Loop" + st);

            } catch (Exception e) {
                Log.v("log_tag", "Error in http connection " + e.toString());
            }
            return "Success";

        }

        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pd.hide();
            pd.dismiss();
        }
    }
}

php code to handle upload image and also create image from base64 encoded data

<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
 echo "Image uploaded";
}else{
 echo "Error uploading image";
}
}
?>

Since most of this is deprecated I've been trying to update the code... it's very frustrating. :) I was able to replace "NameValuePair" with "Pair" and I'm using HttpUrlConnection instead of the apache stuff. But I get lost at the "post" part.

http post - Uploading Images to Server android - Stack Overflow

android http-post image-uploading
Rectangle 27 12

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;


public class MainActivity extends Activity {

    Button btpic, btnup;
    private Uri fileUri;
    String picturePath;
    Uri selectedImage;
    Bitmap photo;
    String ba1;
    public static String URL = "Paste your URL here";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btpic = (Button) findViewById(R.id.cpic);
        btpic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickpic();
            }
        });

        btnup = (Button) findViewById(R.id.up);
        btnup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upload();
            }
        });
    }

    private void upload() {
        // Image location URL
        Log.e("path", "----------------" + picturePath);

        // Image
        Bitmap bm = BitmapFactory.decodeFile(picturePath);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
       //ba1 = Base64.encodeBytes(ba);

        Log.e("base64", "-----" + ba1);

        // Upload image to server
        new uploadToServer().execute();

    }

    private void clickpic() {
        // Check Camera
        if (getApplicationContext().getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // Open default camera
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            // start the image capture Intent
            startActivityForResult(intent, 100);

        } else {
            Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {

            selectedImage = data.getData();
            photo = (Bitmap) data.getExtras().get("data");

            // Cursor to get image uri to display

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            Bitmap photo = (Bitmap) data.getExtras().get("data");
            ImageView imageView = (ImageView) findViewById(R.id.Imageprev);
            imageView.setImageBitmap(photo);
        }
    }

    public class uploadToServer extends AsyncTask<Void, Void, String> {

        private ProgressDialog pd = new ProgressDialog(MainActivity.this);
        protected void onPreExecute() {
            super.onPreExecute();
            pd.setMessage("Wait image uploading!");
            pd.show();
        }

        @Override
        protected String doInBackground(Void... params) {

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("base64", ba1));
            nameValuePairs.add(new BasicNameValuePair("ImageName", System.currentTimeMillis() + ".jpg"));
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(URL);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                String st = EntityUtils.toString(response.getEntity());
                Log.v("log_tag", "In the try Loop" + st);

            } catch (Exception e) {
                Log.v("log_tag", "Error in http connection " + e.toString());
            }
            return "Success";

        }

        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pd.hide();
            pd.dismiss();
        }
    }
}

php code to handle upload image and also create image from base64 encoded data

<?php
error_reporting(E_ALL);
if(isset($_POST['ImageName'])){
$imgname = $_POST['ImageName'];
$imsrc = base64_decode($_POST['base64']);
$fp = fopen($imgname, 'w');
fwrite($fp, $imsrc);
if(fclose($fp)){
 echo "Image uploaded";
}else{
 echo "Error uploading image";
}
}
?>

Since most of this is deprecated I've been trying to update the code... it's very frustrating. :) I was able to replace "NameValuePair" with "Pair" and I'm using HttpUrlConnection instead of the apache stuff. But I get lost at the "post" part.

http post - Uploading Images to Server android - Stack Overflow

android http-post image-uploading
Rectangle 27 4

/**
 * This utility function will upload the file to the Url
 * * @param filePath - absolute path of the file to be uploaded
 * @param postUrl  - Remote Url where the file need to be posted
 * @param contentType - content-type of the uploaded file
 * @throws Exception
 */
public static void postFile(String filePath, String postUrl,
        String pictureTitleStr, String pseudoTextStr)
        throws Exception {

    String url = postUrl;
    HttpURLConnection conn = null;
    final String CrLf = "\r\n";
    JSONObject json = new JSONObject();
    int bytesRead = 0;


    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "xxxxxxxx";
    String EndBoundary = "";
    int maxBufferSize = 1 * 1024 * 1024;

    HttpResponse response = null;

  // Having HttpClient to respond to both HTTP and HTTPS url connection by accepting the urls along with keystore / trust certificates 

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore
                .getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUserAgent(params, "YourAppName/1.1");
        HttpConnectionParams.setStaleCheckingEnabled(params, false);
        HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
        HttpConnectionParams.setSoTimeout(params, 20 * 1000);
        HttpConnectionParams.setSocketBufferSize(params, 8192);
        HttpClientParams.setRedirecting(params, false);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory
                .getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(
                params, registry);

        mHttpClient = new DefaultHttpClient(ccm, params);



    } catch (Exception e) {

    }

    String base64EncodedCredentials = Base64.encodeToString((userName + ":" + password).getBytes("US-ASCII"),
            Base64.DEFAULT);
    System.out.println("Encoded Credit " + base64EncodedCredentials);

            json.put("pseudo", pseudoTextStr);
            json.put("title", pictureTitleStr);

           String jsonStr = json.toString(); 
 //   System.out.println("JSON VALUE  " + jsonStr);

    URL url2 = new URL(postUrl);



    Bitmap bm = BitmapFactory.decodeFile(filePath);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 25, baos); // bm is the bitmap object
    byte[] b = baos.toByteArray();

    String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);


    String str = twoHyphens + boundary + lineEnd;
    String str2 = "Content-Disposition: form-data; name=\"jsonFile\"";
    String str3 = "Content-Type: application/json";
    String str4 = "Content-Disposition: form-data; name=\"imgName\"";
    String str5 = "Content-Type: image/jpeg";
    String str6 = twoHyphens + boundary + twoHyphens;



    String StrTotal = str + str2 + "\r\n" + str3 + "\r\n" +"\r\n" + jsonStr + "\r\n" + str
            + str4 + "\r\n" + str5 + "\r\n"+"\r\n"+ encodedImage + "\r\n" + str6;

    //System.out.print("Multipart request string is "+StrTotal);

 HttpPost post = new HttpPost(postUrl);


post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(
                userName, password), "UTF-8", false));
post.addHeader("Content-Type","multipart/form-data;boundary="+boundary);
// System.out.println("Sending Post proxy request: " + post);

 StringEntity se = new StringEntity(StrTotal);
 se.setContentEncoding("UTF-8");
 post.setEntity(se);
 response = mHttpClient.execute(post);

/* Checking response */

statusCode = response.getStatusLine().getStatusCode();
System.out.println("Http Execute finish " + statusCode);

HttpEntity entity = response.getEntity();
String getResponseText = entity.toString(); // EntityUtils.toString(entity);
System.out.println(" Post Response Text from Server : "
        + getResponseText);



}

thanks for the answer it helped me solve my problem. Meanwhile, can you please help me with posting multiple image along with the json. I have posted a question here, please have a look : stackoverflow.com/questions/40279640/

Uploading image to server in Multipart along with JSON data in Android...

android image multipart
Rectangle 27 3

Assuming you know how to load the PDF in to a byte array you've got to get it Base64 encoded and then post that to server using MIME multipart encoding.

You can utilise the MSXML libraries ability to perform Base64 encoding. See this link for details.

Once you have the PDF as a Bas64 string you need to package that as MIME multipart. You can use XMLHTTP object from MSXML to perform that posting for you:-

sEntityBody = "----boundary" & vbCrLf
sEntityBody = sEntityBody & "Content-Disposition: form-data; name=fileInputElementName; filename=""" + sFileName + """" & vbCrLf
sEntityBody = sEntityBody & "Content-Transfer-Encoding: base64" & vbCrLf
sEntityBody = sEntityBody & "Content-Type: application/pdf" &  vbCrLf & vbCrLf
sEntityBody = sEntityBody & sPDFBase64 & vbCrLf
sEntityBody = sEntityBody & "-----boundary--" & vbCrLf & vbCrLf

Set xhr = New MSXML2.XMLHTTP30
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=-----boundary")
xhr.Open "POST", sUrl, False
xhr.send sEntityBody

Perhaps not elegant or efficient but it should it work.

Hi, I'm getting an unexpected error message when using your code above :-(

Its working now but the send() command is nagging when I send the sEntityBody to it. it gives me an error that the parameter is incorrect.

@Lennie: The last comment is unclear its working now? What did you have to change?

Content-Transfer-Encoding
send
xhr.send CVar(sBody)

vb6 - HTTP Post/Upload From Visual Basic 6 - Stack Overflow

vb6
Rectangle 27 7

If you don't want to import the whole of MGTwitterEngine and you aren't doing an asynchronous request Then you can use http://www.chrisumbel.com/article/basic_authentication_iphone_cocoa_touch

To base64 encode the Username and password So replace

NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];

with

NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];
static char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation Base64
+(NSString *)encode:(NSData *)plainText {
    int encodedLength = (((([plainText length] % 3) + [plainText length]) / 3) * 4) + 1;
    unsigned char *outputBuffer = malloc(encodedLength);
    unsigned char *inputBuffer = (unsigned char *)[plainText bytes];

    NSInteger i;
    NSInteger j = 0;
    int remain;

    for(i = 0; i < [plainText length]; i += 3) {
        remain = [plainText length] - i;

        outputBuffer[j++] = alphabet[(inputBuffer[i] & 0xFC) >> 2];
        outputBuffer[j++] = alphabet[((inputBuffer[i] & 0x03) << 4) | 
                                     ((remain > 1) ? ((inputBuffer[i + 1] & 0xF0) >> 4): 0)];

        if(remain > 1)
            outputBuffer[j++] = alphabet[((inputBuffer[i + 1] & 0x0F) << 2)
                                         | ((remain > 2) ? ((inputBuffer[i + 2] & 0xC0) >> 6) : 0)];
        else 
            outputBuffer[j++] = '=';

        if(remain > 2)
            outputBuffer[j++] = alphabet[inputBuffer[i + 2] & 0x3F];
        else
            outputBuffer[j++] = '=';            
    }

    outputBuffer[j] = 0;

    NSString *result = [NSString stringWithCString:outputBuffer length:strlen(outputBuffer)];
    free(outputBuffer);

    return result;
}
@end

iphone - NSURLConnection and Basic HTTP Authentication in iOS - Stack ...

ios iphone objective-c nsurlconnection
Rectangle 27 7

If you don't want to import the whole of MGTwitterEngine and you aren't doing an asynchronous request Then you can use http://www.chrisumbel.com/article/basic_authentication_iphone_cocoa_touch

To base64 encode the Username and password So replace

NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];

with

NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];
static char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation Base64
+(NSString *)encode:(NSData *)plainText {
    int encodedLength = (((([plainText length] % 3) + [plainText length]) / 3) * 4) + 1;
    unsigned char *outputBuffer = malloc(encodedLength);
    unsigned char *inputBuffer = (unsigned char *)[plainText bytes];

    NSInteger i;
    NSInteger j = 0;
    int remain;

    for(i = 0; i < [plainText length]; i += 3) {
        remain = [plainText length] - i;

        outputBuffer[j++] = alphabet[(inputBuffer[i] & 0xFC) >> 2];
        outputBuffer[j++] = alphabet[((inputBuffer[i] & 0x03) << 4) | 
                                     ((remain > 1) ? ((inputBuffer[i + 1] & 0xF0) >> 4): 0)];

        if(remain > 1)
            outputBuffer[j++] = alphabet[((inputBuffer[i + 1] & 0x0F) << 2)
                                         | ((remain > 2) ? ((inputBuffer[i + 2] & 0xC0) >> 6) : 0)];
        else 
            outputBuffer[j++] = '=';

        if(remain > 2)
            outputBuffer[j++] = alphabet[inputBuffer[i + 2] & 0x3F];
        else
            outputBuffer[j++] = '=';            
    }

    outputBuffer[j] = 0;

    NSString *result = [NSString stringWithCString:outputBuffer length:strlen(outputBuffer)];
    free(outputBuffer);

    return result;
}
@end

iphone - NSURLConnection and Basic HTTP Authentication in iOS - Stack ...

ios iphone objective-c nsurlconnection
Rectangle 27 6

Try converting your image to a Base64 string value for BINVAL instead of using UTF-8 encoding.

Base64
The <PHOTO/> element SHOULD contain a <BINVAL/> child whose XML character data is Base64-encoded data for the avatar image.
The image data MUST conform to the base64Binary datatype [7] and thus be encoded in accordance with Section 6.8 of RFC 2045 [8], which recommends that base64 data should have lines limited to at most 76 characters in length. However, any whitespace characters (e.g., '\r' and '\n') MUST be ignored.

Hi @KeithOYS I am using following IQ to update vCard. <iq type="set" id="71125AFE-9323-4CBA-B1BD-89DE63058D70"><Test Name xmlns="vcard-temp"/></iq>. When I use whitespace character in stanza for nick name it's producing error. What should I do to avoid this situation?

ios - XMPPFramework - Upload Profile or Avatar Image - Stack Overflow

ios objective-c xmpp xmppframework
Rectangle 27 2

I looked into using Volley as a mechanism to transport large JSON objects to a server and found this answer. This answer essentially proved that Volley would be a bad idea for what I wanted.

I switched to OkHttp and now use their streaming methods allowing the JSON to be streamed to the server and then read the response with a streamlined approach. I used the GSON library to parse the response as OKHttp allows the response JSON/Object to be streamed into a reader object which Gson then uses for internal streaming and parsing to an POJO class.

The ony reason why I did not switch to a Multi-Part request was due to the server side implementation being rigid and unchangeable to cover for Multi-Part requests, it strictly expected a JSON representation of data and files.

For handling Base64 Images on Android I severely reccomend not using the String representation and merely converting to Bytes to save on using an excessive amount of memory. I read this article on String memory usage and management. With the Bytes you may easily transport the data without leaving a massive footprint on memory.

For Displaying the images I still avoid the bytes to String conversion by using the Image library Glide. They allow you to pass in a byte[] which was of massive convenience.

Android Image upload/download with Base64 into JSON causes Out of memo...

android image base64 gson android-volley
Rectangle 27 3

You should first consider this: the size of the upload is limited. The limit depends on browser, OS and server environment. You can have a look at this article: http://www.motobit.com/help/scptutl/pa98.htm

In general you can try something like this: first we need a function to convert the dataURI to a blob:

function convertDataURItoBlob(dataURI) {
        'use strict'

        var byteString,
            mimestring

        if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
            byteString = atob(dataURI.split(',')[1])
        } else {
            byteString = decodeURI(dataURI.split(',')[1])
        }

        mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]


        var content = new Array();
        for (var i = 0; i < byteString.length; i++) {
            content[i] = byteString.charCodeAt(i)
        }
        var rawContent = new Uint8Array(content),
            returnBlob = new Blob([rawContent], {type: mimestring})

        return returnBlob;

}

and next a function for the upload of the file, using XMLHttpRequest2:

function upload(blob) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/yourServerEndPoint', true);
  xhr.onload = function(e) { ... };

  xhr.send(blob);
}

Now you can pass your strDataURI to the first function and then upload the file with the second function.

I don't need to upload. I need to convert my canvas in PNG. My problem is exporting canvas. For example: I have a canvas like 100x100 centimeters at 72 DPI resolution, but I need to resize to 300 dpi. The final canvas as about 30000x30000 pixels (100 centimeters * 300 is about 30000 pixels) and toDataURL function won't work. I thnk that problem is related to <canvas> size limit, like this stackoverflow.com/questions/6081483/ Thank You for your reply.

canvas.toDataURL() for large canvas - Stack Overflow

canvas html5-canvas fabricjs
Rectangle 27 3

You should first consider this: the size of the upload is limited. The limit depends on browser, OS and server environment. You can have a look at this article: http://www.motobit.com/help/scptutl/pa98.htm

In general you can try something like this: first we need a function to convert the dataURI to a blob:

function convertDataURItoBlob(dataURI) {
        'use strict'

        var byteString,
            mimestring

        if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
            byteString = atob(dataURI.split(',')[1])
        } else {
            byteString = decodeURI(dataURI.split(',')[1])
        }

        mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]


        var content = new Array();
        for (var i = 0; i < byteString.length; i++) {
            content[i] = byteString.charCodeAt(i)
        }
        var rawContent = new Uint8Array(content),
            returnBlob = new Blob([rawContent], {type: mimestring})

        return returnBlob;

}

and next a function for the upload of the file, using XMLHttpRequest2:

function upload(blob) {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/yourServerEndPoint', true);
  xhr.onload = function(e) { ... };

  xhr.send(blob);
}

Now you can pass your strDataURI to the first function and then upload the file with the second function.

I don't need to upload. I need to convert my canvas in PNG. My problem is exporting canvas. For example: I have a canvas like 100x100 centimeters at 72 DPI resolution, but I need to resize to 300 dpi. The final canvas as about 30000x30000 pixels (100 centimeters * 300 is about 30000 pixels) and toDataURL function won't work. I thnk that problem is related to <canvas> size limit, like this stackoverflow.com/questions/6081483/ Thank You for your reply.

canvas.toDataURL() for large canvas - Stack Overflow

canvas html5-canvas fabricjs
Rectangle 27 3

def image_params
    img_params = params.require(:image).permit(:image, :filename, :date_uploaded, :lat, :lon, :update_ticks, image_comments: [:comment, :date_created, :user_id]).merge(user_id: current_user.id, company_id: current_user.company_id)
    img_params.merge(convert_data_uri_to_upload(img_params))
    img_params
  end

  def split_base64(uri_str)
    if uri_str.match(%r{^data:(.*?);(.*?),(.*)$})
      uri = Hash.new
      uri[:type] = $1 # "image/gif"
      uri[:encoder] = $2 # "base64"
      uri[:data] = $3 # data string
      uri[:extension] = $1.split('/')[1] # "gif"
      return uri
    else
      return nil
    end
  end

  def convert_data_uri_to_upload(obj_hash)
    if obj_hash[:image].try(:match, %r{^data:(.*?);(.*?),(.*)$})
      image_data = split_base64(obj_hash[:image])
      image_data_string = image_data[:data]
      image_data_binary = Base64.decode64(image_data_string)

      temp_img_file = Tempfile.new(obj_hash[:filename])
      temp_img_file.binmode
      temp_img_file << image_data_binary
      temp_img_file.rewind

      img_params = {:filename => obj_hash[:filename], :type => image_data[:type], :tempfile => temp_img_file}
      uploaded_file = ActionDispatch::Http::UploadedFile.new(img_params)

      obj_hash[:url_large] = uploaded_file
      obj_hash.delete(:image)
    end

    return obj_hash    
  end

ruby on rails - CarrierWave Base64 Image Upload - Stack Overflow

ruby-on-rails image carrierwave
Rectangle 27 2

@Override
protected String doInBackground(String... str) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    String encodedImage = bitmapToString(mBitmap);

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("data", encodedImage));

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(
                "http://192.168.0.107:8300/upload/upload");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        String the_string_response = convertResponseToString(response);
        return the_string_response;
    } catch (Exception e) {
        System.out.println("Error in http connection " + e.toString());
        return "error";
    }
}

public String bitmapToString(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String temp = null;
    try {
        System.gc();
        temp = Base64.encodeToString(b, Base64.DEFAULT);
    } catch (Exception e) {
        e.printStackTrace();
    } catch (OutOfMemoryError e) {
        baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
        b = baos.toByteArray();
        temp = Base64.encodeToString(b, Base64.DEFAULT);
        Log.e("PictureDemo", "Out of memory error catched");
    }
    return temp;
}

private String convertResponseToString(HttpResponse response)
        throws IllegalStateException, IOException {

    String res = "";
    StringBuffer buffer = new StringBuffer();
    inputStream = response.getEntity().getContent();
    int contentLength = (int) response.getEntity().getContentLength();
    if (contentLength < 0) {
    } else {
        byte[] data = new byte[512];
        int len = 0;
        try {
            while (-1 != (len = inputStream.read(data))) {
                buffer.append(new String(data, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        res = buffer.toString();
    }
    return res;
}

java - Send Image in JSON request - Stack Overflow

java android json rest
Rectangle 27 4

You cannot just include binary image data in a JSON request. JSON requires text representation, so if you do this, you must convert it to string (e.g. base64 encoding), use that in the JSON, and then the server code would presumably convert the base64 string back to binary data before attempting to use it.

But if you were base64 encoding of the image, it might look something like:

// get image data

let imageData = UIImagePNGRepresentation(image)

// convert to base64

let base64String = imageData.base64EncodedStringWithOptions(nil)

// build parameters

let parameters = ["image": ["file" : base64String], "access_token" : accessToken]

// get JSON

var error: NSError?
let data = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &error)
assert(data != nil, "Unable to serialize \(error)")

// build request

let url = NSURL(string: "http://example.com/upload")!
let request = NSMutableURLRequest(URL: url)
request.addValue("text/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"

let task = NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data) { data, response, error in
    // check for basic connectivity errors

    if error != nil {
        println("error: \(error)")
        return
    }

    // check for server errors

    if let httpResponse = response as? NSHTTPURLResponse, let statusCode = httpResponse.statusCode as Int? {
        if statusCode != 200 {
            println("status code is \(statusCode)")
        }
    }

    // check for details of app-level server response, e.g. if JSON that was dictionary:

    var parseError: NSError?
    if let responseObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError) as? [String : AnyObject] {
        println(responseObject)
    } else {
        println("JSON parse failed: \(parseError)")
        println("response was: \(response)")
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString was: \(responseString)")
    }
}
task.resume()
// build parameters

let parameters = ["image": ["file" : base64String], "access_token" : accessToken] as [String : AnyObject]

// build request

let urlString = "http://example.com/upload"

Alamofire.request(.POST, urlString, parameters: parameters, encoding: .JSON)
    .responseJSON(options: nil) { request, response, responseObject, error in
        if error != nil {
            println(error)
        } else {
            println(responseObject)
        }
    }

But both of the above are making assumptions about the nature of the response, that the server is base64 decoding the image data from the JSON, etc., but hopefully this illustrates the basic patterns.

application/x-www-form-urlencoded

Thanks! @Rob It seems like your solution should work, but I already found a simpler implementation using AFNetworking (posted answer)

@mohonish - Great. If using Swift, I'd personally use Alamofire (same author as AFNetworking; doesn't use the now deprecated NSURLConnection which AFHTTPRequestOperationManager does; etc.), but both AFNetworking and Alamofire make your life much easier than writing your own NSURLSession code.

ios - How can we upload multipart form data with nested JSON parameter...

ios json swift nsurlsession alamofire