How upload Image on stripe?












0















I added all things related to stripe server guide but did not work for
me Here is my code i did not added stripe key and please also guide me
where i add stripe key and yet in response null return in body.please
guide me if you have any idea.




 try {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

// Change base URL to your upload server URL.
service = new Retrofit.Builder().baseUrl("https://uploads.stripe.com/v1/files/").client(client).build().create(InterfaceService.class);
} catch (Exception e) {
e.printStackTrace();
}

// File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), actualFile);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", fileName, reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");



// Log.d("THIS", data.getData().getPath());

Map<String, RequestBody> fileUploadParams = new HashMap<>();
fileUploadParams.put("purpose", InterfaceService.createRequestBody("identity_document"));
fileUploadParams.put("file", InterfaceService.createRequestBody(actualFile));

retrofit2.Call<ResponseBody> req = service.uploadFileWithPartMap(fileUploadParams, body);
req.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {









share|improve this question
























  • Possible duplicate of How to Upload Image file in Retrofit 2
    – koksalb
    Nov 19 '18 at 18:02










  • for stripe i am confused about request body and stripe key usage
    – humayoon siddique
    Nov 19 '18 at 18:03
















0















I added all things related to stripe server guide but did not work for
me Here is my code i did not added stripe key and please also guide me
where i add stripe key and yet in response null return in body.please
guide me if you have any idea.




 try {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

// Change base URL to your upload server URL.
service = new Retrofit.Builder().baseUrl("https://uploads.stripe.com/v1/files/").client(client).build().create(InterfaceService.class);
} catch (Exception e) {
e.printStackTrace();
}

// File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), actualFile);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", fileName, reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");



// Log.d("THIS", data.getData().getPath());

Map<String, RequestBody> fileUploadParams = new HashMap<>();
fileUploadParams.put("purpose", InterfaceService.createRequestBody("identity_document"));
fileUploadParams.put("file", InterfaceService.createRequestBody(actualFile));

retrofit2.Call<ResponseBody> req = service.uploadFileWithPartMap(fileUploadParams, body);
req.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {









share|improve this question
























  • Possible duplicate of How to Upload Image file in Retrofit 2
    – koksalb
    Nov 19 '18 at 18:02










  • for stripe i am confused about request body and stripe key usage
    – humayoon siddique
    Nov 19 '18 at 18:03














0












0








0


1






I added all things related to stripe server guide but did not work for
me Here is my code i did not added stripe key and please also guide me
where i add stripe key and yet in response null return in body.please
guide me if you have any idea.




 try {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

// Change base URL to your upload server URL.
service = new Retrofit.Builder().baseUrl("https://uploads.stripe.com/v1/files/").client(client).build().create(InterfaceService.class);
} catch (Exception e) {
e.printStackTrace();
}

// File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), actualFile);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", fileName, reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");



// Log.d("THIS", data.getData().getPath());

Map<String, RequestBody> fileUploadParams = new HashMap<>();
fileUploadParams.put("purpose", InterfaceService.createRequestBody("identity_document"));
fileUploadParams.put("file", InterfaceService.createRequestBody(actualFile));

retrofit2.Call<ResponseBody> req = service.uploadFileWithPartMap(fileUploadParams, body);
req.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {









share|improve this question
















I added all things related to stripe server guide but did not work for
me Here is my code i did not added stripe key and please also guide me
where i add stripe key and yet in response null return in body.please
guide me if you have any idea.




 try {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

// Change base URL to your upload server URL.
service = new Retrofit.Builder().baseUrl("https://uploads.stripe.com/v1/files/").client(client).build().create(InterfaceService.class);
} catch (Exception e) {
e.printStackTrace();
}

// File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), actualFile);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", fileName, reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "upload_test");



// Log.d("THIS", data.getData().getPath());

Map<String, RequestBody> fileUploadParams = new HashMap<>();
fileUploadParams.put("purpose", InterfaceService.createRequestBody("identity_document"));
fileUploadParams.put("file", InterfaceService.createRequestBody(actualFile));

retrofit2.Call<ResponseBody> req = service.uploadFileWithPartMap(fileUploadParams, body);
req.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {






android android-studio gson retrofit react-native-stripe-api






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 11:45







humayoon siddique

















asked Nov 19 '18 at 17:56









humayoon siddiquehumayoon siddique

236320




236320












  • Possible duplicate of How to Upload Image file in Retrofit 2
    – koksalb
    Nov 19 '18 at 18:02










  • for stripe i am confused about request body and stripe key usage
    – humayoon siddique
    Nov 19 '18 at 18:03


















  • Possible duplicate of How to Upload Image file in Retrofit 2
    – koksalb
    Nov 19 '18 at 18:02










  • for stripe i am confused about request body and stripe key usage
    – humayoon siddique
    Nov 19 '18 at 18:03
















Possible duplicate of How to Upload Image file in Retrofit 2
– koksalb
Nov 19 '18 at 18:02




Possible duplicate of How to Upload Image file in Retrofit 2
– koksalb
Nov 19 '18 at 18:02












for stripe i am confused about request body and stripe key usage
– humayoon siddique
Nov 19 '18 at 18:03




for stripe i am confused about request body and stripe key usage
– humayoon siddique
Nov 19 '18 at 18:03












1 Answer
1






active

oldest

votes


















0















here is complete solution for upload file on stripe




 multipart = new MultipartUtility("https://uploads.stripe.com/v1/files", "");

// In your case you are not adding form data so ignore this
/*This is to add parameter values */
multipart.addFormField("purpose", "identity_document");
multipart.addFilePart("file", new File(frontPath));
response = multipart.finish();



Here is Utility Class




public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "rn";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;

/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* @param requestURL
* @param charset
* @throws IOException
*/
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset;

// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setConnectTimeout(3000000); // 90 sec
httpConn.setReadTimeout(3000000);
httpConn.setChunkedStreamingMode(1024);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
httpConn.setRequestProperty("Authorization", "Bearer " + STRIPE_KEY);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream),
true);
}

/**
* Adds a form field to the request
*
* @param name field name
* @param value field value
*/
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name="" + name + """)
.append(LINE_FEED);
writer.append("Content-Type: image/jpeg; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}

/**
* Adds a upload file section to the request
*
* @param fieldName name attribute in <input type="file" name="..." />
* @param uploadFile a File to be uploaded
* @throws IOException
*/
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name="" + fieldName
+ ""; filename="" + fileName + """)
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();

FileInputStream inputStream = new FileInputStream(uploadFile);
byte buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}

/**
* Adds a header field to the request.
*
* @param name - name of the header field
* @param value - value of the header field
*/
public void addHeaderField(String name, String value) {
httpConn.setRequestProperty(name, value);
// writer.append(name + ": " + value).append(LINE_FEED);
// writer.flush();
}

/**
* Completes the request and receives response from the server.
*
* @return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* @throws IOException
*/
public String finish() throws IOException {
List<String> response = new ArrayList<String>();
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();

// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
httpConn.disconnect();
return builder.toString();
} else {
return "Server returned non-OK status: " + status;
}

}

}





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53380219%2fhow-upload-image-on-stripe%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0















    here is complete solution for upload file on stripe




     multipart = new MultipartUtility("https://uploads.stripe.com/v1/files", "");

    // In your case you are not adding form data so ignore this
    /*This is to add parameter values */
    multipart.addFormField("purpose", "identity_document");
    multipart.addFilePart("file", new File(frontPath));
    response = multipart.finish();



    Here is Utility Class




    public class MultipartUtility {
    private final String boundary;
    private static final String LINE_FEED = "rn";
    private HttpURLConnection httpConn;
    private String charset;
    private OutputStream outputStream;
    private PrintWriter writer;

    /**
    * This constructor initializes a new HTTP POST request with content type
    * is set to multipart/form-data
    *
    * @param requestURL
    * @param charset
    * @throws IOException
    */
    public MultipartUtility(String requestURL, String charset)
    throws IOException {
    this.charset = charset;

    // creates a unique boundary based on time stamp
    boundary = "===" + System.currentTimeMillis() + "===";
    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setConnectTimeout(3000000); // 90 sec
    httpConn.setReadTimeout(3000000);
    httpConn.setChunkedStreamingMode(1024);
    httpConn.setRequestProperty("Content-Type",
    "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("Authorization", "Bearer " + STRIPE_KEY);
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream),
    true);
    }

    /**
    * Adds a form field to the request
    *
    * @param name field name
    * @param value field value
    */
    public void addFormField(String name, String value) {
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name="" + name + """)
    .append(LINE_FEED);
    writer.append("Content-Type: image/jpeg; charset=" + charset).append(
    LINE_FEED);
    writer.append(LINE_FEED);
    writer.append(value).append(LINE_FEED);
    writer.flush();
    }

    /**
    * Adds a upload file section to the request
    *
    * @param fieldName name attribute in <input type="file" name="..." />
    * @param uploadFile a File to be uploaded
    * @throws IOException
    */
    public void addFilePart(String fieldName, File uploadFile)
    throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
    "Content-Disposition: form-data; name="" + fieldName
    + ""; filename="" + fileName + """)
    .append(LINE_FEED);
    writer.append(
    "Content-Type: "
    + URLConnection.guessContentTypeFromName(fileName))
    .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();
    writer.append(LINE_FEED);
    writer.flush();
    }

    /**
    * Adds a header field to the request.
    *
    * @param name - name of the header field
    * @param value - value of the header field
    */
    public void addHeaderField(String name, String value) {
    httpConn.setRequestProperty(name, value);
    // writer.append(name + ": " + value).append(LINE_FEED);
    // writer.flush();
    }

    /**
    * Completes the request and receives response from the server.
    *
    * @return a list of Strings as response in case the server returned
    * status OK, otherwise an exception is thrown.
    * @throws IOException
    */
    public String finish() throws IOException {
    List<String> response = new ArrayList<String>();
    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    httpConn.getInputStream()));
    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
    builder.append(line);
    }
    reader.close();
    httpConn.disconnect();
    return builder.toString();
    } else {
    return "Server returned non-OK status: " + status;
    }

    }

    }





    share|improve this answer


























      0















      here is complete solution for upload file on stripe




       multipart = new MultipartUtility("https://uploads.stripe.com/v1/files", "");

      // In your case you are not adding form data so ignore this
      /*This is to add parameter values */
      multipart.addFormField("purpose", "identity_document");
      multipart.addFilePart("file", new File(frontPath));
      response = multipart.finish();



      Here is Utility Class




      public class MultipartUtility {
      private final String boundary;
      private static final String LINE_FEED = "rn";
      private HttpURLConnection httpConn;
      private String charset;
      private OutputStream outputStream;
      private PrintWriter writer;

      /**
      * This constructor initializes a new HTTP POST request with content type
      * is set to multipart/form-data
      *
      * @param requestURL
      * @param charset
      * @throws IOException
      */
      public MultipartUtility(String requestURL, String charset)
      throws IOException {
      this.charset = charset;

      // creates a unique boundary based on time stamp
      boundary = "===" + System.currentTimeMillis() + "===";
      URL url = new URL(requestURL);
      httpConn = (HttpURLConnection) url.openConnection();
      httpConn.setUseCaches(false);
      httpConn.setDoOutput(true); // indicates POST method
      httpConn.setDoInput(true);
      httpConn.setConnectTimeout(3000000); // 90 sec
      httpConn.setReadTimeout(3000000);
      httpConn.setChunkedStreamingMode(1024);
      httpConn.setRequestProperty("Content-Type",
      "multipart/form-data; boundary=" + boundary);
      httpConn.setRequestProperty("Authorization", "Bearer " + STRIPE_KEY);
      outputStream = httpConn.getOutputStream();
      writer = new PrintWriter(new OutputStreamWriter(outputStream),
      true);
      }

      /**
      * Adds a form field to the request
      *
      * @param name field name
      * @param value field value
      */
      public void addFormField(String name, String value) {
      writer.append("--" + boundary).append(LINE_FEED);
      writer.append("Content-Disposition: form-data; name="" + name + """)
      .append(LINE_FEED);
      writer.append("Content-Type: image/jpeg; charset=" + charset).append(
      LINE_FEED);
      writer.append(LINE_FEED);
      writer.append(value).append(LINE_FEED);
      writer.flush();
      }

      /**
      * Adds a upload file section to the request
      *
      * @param fieldName name attribute in <input type="file" name="..." />
      * @param uploadFile a File to be uploaded
      * @throws IOException
      */
      public void addFilePart(String fieldName, File uploadFile)
      throws IOException {
      String fileName = uploadFile.getName();
      writer.append("--" + boundary).append(LINE_FEED);
      writer.append(
      "Content-Disposition: form-data; name="" + fieldName
      + ""; filename="" + fileName + """)
      .append(LINE_FEED);
      writer.append(
      "Content-Type: "
      + URLConnection.guessContentTypeFromName(fileName))
      .append(LINE_FEED);
      writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
      writer.append(LINE_FEED);
      writer.flush();

      FileInputStream inputStream = new FileInputStream(uploadFile);
      byte buffer = new byte[4096];
      int bytesRead = -1;
      while ((bytesRead = inputStream.read(buffer)) != -1) {
      outputStream.write(buffer, 0, bytesRead);
      }
      outputStream.flush();
      inputStream.close();
      writer.append(LINE_FEED);
      writer.flush();
      }

      /**
      * Adds a header field to the request.
      *
      * @param name - name of the header field
      * @param value - value of the header field
      */
      public void addHeaderField(String name, String value) {
      httpConn.setRequestProperty(name, value);
      // writer.append(name + ": " + value).append(LINE_FEED);
      // writer.flush();
      }

      /**
      * Completes the request and receives response from the server.
      *
      * @return a list of Strings as response in case the server returned
      * status OK, otherwise an exception is thrown.
      * @throws IOException
      */
      public String finish() throws IOException {
      List<String> response = new ArrayList<String>();
      writer.append(LINE_FEED).flush();
      writer.append("--" + boundary + "--").append(LINE_FEED);
      writer.close();

      // checks server's status code first
      int status = httpConn.getResponseCode();
      if (status == HttpURLConnection.HTTP_OK) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(
      httpConn.getInputStream()));
      StringBuilder builder = new StringBuilder();
      String line;
      while ((line = reader.readLine()) != null) {
      builder.append(line);
      }
      reader.close();
      httpConn.disconnect();
      return builder.toString();
      } else {
      return "Server returned non-OK status: " + status;
      }

      }

      }





      share|improve this answer
























        0












        0








        0







        here is complete solution for upload file on stripe




         multipart = new MultipartUtility("https://uploads.stripe.com/v1/files", "");

        // In your case you are not adding form data so ignore this
        /*This is to add parameter values */
        multipart.addFormField("purpose", "identity_document");
        multipart.addFilePart("file", new File(frontPath));
        response = multipart.finish();



        Here is Utility Class




        public class MultipartUtility {
        private final String boundary;
        private static final String LINE_FEED = "rn";
        private HttpURLConnection httpConn;
        private String charset;
        private OutputStream outputStream;
        private PrintWriter writer;

        /**
        * This constructor initializes a new HTTP POST request with content type
        * is set to multipart/form-data
        *
        * @param requestURL
        * @param charset
        * @throws IOException
        */
        public MultipartUtility(String requestURL, String charset)
        throws IOException {
        this.charset = charset;

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setConnectTimeout(3000000); // 90 sec
        httpConn.setReadTimeout(3000000);
        httpConn.setChunkedStreamingMode(1024);
        httpConn.setRequestProperty("Content-Type",
        "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("Authorization", "Bearer " + STRIPE_KEY);
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream),
        true);
        }

        /**
        * Adds a form field to the request
        *
        * @param name field name
        * @param value field value
        */
        public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name="" + name + """)
        .append(LINE_FEED);
        writer.append("Content-Type: image/jpeg; charset=" + charset).append(
        LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
        }

        /**
        * Adds a upload file section to the request
        *
        * @param fieldName name attribute in <input type="file" name="..." />
        * @param uploadFile a File to be uploaded
        * @throws IOException
        */
        public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
        "Content-Disposition: form-data; name="" + fieldName
        + ""; filename="" + fileName + """)
        .append(LINE_FEED);
        writer.append(
        "Content-Type: "
        + URLConnection.guessContentTypeFromName(fileName))
        .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();
        writer.append(LINE_FEED);
        writer.flush();
        }

        /**
        * Adds a header field to the request.
        *
        * @param name - name of the header field
        * @param value - value of the header field
        */
        public void addHeaderField(String name, String value) {
        httpConn.setRequestProperty(name, value);
        // writer.append(name + ": " + value).append(LINE_FEED);
        // writer.flush();
        }

        /**
        * Completes the request and receives response from the server.
        *
        * @return a list of Strings as response in case the server returned
        * status OK, otherwise an exception is thrown.
        * @throws IOException
        */
        public String finish() throws IOException {
        List<String> response = new ArrayList<String>();
        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
        httpConn.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
        builder.append(line);
        }
        reader.close();
        httpConn.disconnect();
        return builder.toString();
        } else {
        return "Server returned non-OK status: " + status;
        }

        }

        }





        share|improve this answer













        here is complete solution for upload file on stripe




         multipart = new MultipartUtility("https://uploads.stripe.com/v1/files", "");

        // In your case you are not adding form data so ignore this
        /*This is to add parameter values */
        multipart.addFormField("purpose", "identity_document");
        multipart.addFilePart("file", new File(frontPath));
        response = multipart.finish();



        Here is Utility Class




        public class MultipartUtility {
        private final String boundary;
        private static final String LINE_FEED = "rn";
        private HttpURLConnection httpConn;
        private String charset;
        private OutputStream outputStream;
        private PrintWriter writer;

        /**
        * This constructor initializes a new HTTP POST request with content type
        * is set to multipart/form-data
        *
        * @param requestURL
        * @param charset
        * @throws IOException
        */
        public MultipartUtility(String requestURL, String charset)
        throws IOException {
        this.charset = charset;

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setConnectTimeout(3000000); // 90 sec
        httpConn.setReadTimeout(3000000);
        httpConn.setChunkedStreamingMode(1024);
        httpConn.setRequestProperty("Content-Type",
        "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("Authorization", "Bearer " + STRIPE_KEY);
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream),
        true);
        }

        /**
        * Adds a form field to the request
        *
        * @param name field name
        * @param value field value
        */
        public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name="" + name + """)
        .append(LINE_FEED);
        writer.append("Content-Type: image/jpeg; charset=" + charset).append(
        LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
        }

        /**
        * Adds a upload file section to the request
        *
        * @param fieldName name attribute in <input type="file" name="..." />
        * @param uploadFile a File to be uploaded
        * @throws IOException
        */
        public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append(
        "Content-Disposition: form-data; name="" + fieldName
        + ""; filename="" + fileName + """)
        .append(LINE_FEED);
        writer.append(
        "Content-Type: "
        + URLConnection.guessContentTypeFromName(fileName))
        .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        inputStream.close();
        writer.append(LINE_FEED);
        writer.flush();
        }

        /**
        * Adds a header field to the request.
        *
        * @param name - name of the header field
        * @param value - value of the header field
        */
        public void addHeaderField(String name, String value) {
        httpConn.setRequestProperty(name, value);
        // writer.append(name + ": " + value).append(LINE_FEED);
        // writer.flush();
        }

        /**
        * Completes the request and receives response from the server.
        *
        * @return a list of Strings as response in case the server returned
        * status OK, otherwise an exception is thrown.
        * @throws IOException
        */
        public String finish() throws IOException {
        List<String> response = new ArrayList<String>();
        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
        httpConn.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
        builder.append(line);
        }
        reader.close();
        httpConn.disconnect();
        return builder.toString();
        } else {
        return "Server returned non-OK status: " + status;
        }

        }

        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 '18 at 12:12









        humayoon siddiquehumayoon siddique

        236320




        236320






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53380219%2fhow-upload-image-on-stripe%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            SQL update select statement

            'app-layout' is not a known element: how to share Component with different Modules