如何在条带上上传图像?

时间:2018-11-19 17:56:19

标签: android gson retrofit react-native-stripe-api

  

我添加了与条带服务器指南有关的所有内容,但不适用于   我这是我的代码,我没有添加条纹键,也请指导我   我在其中添加条带键,但仍在body.please中返回null   有什么想法可以指导我。

 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) {

1 个答案:

答案 0 :(得分:1)

  

这是在条带上上传文件的完整解决方案

 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();
  

这是实用程序类

public class MultipartUtility {
    private final String boundary;
    private static final String LINE_FEED = "\r\n";
    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;
        }

    }

}