leancloud通过REST API上传文件

实现思路

1、通过fileTokens接口获取上传的token和key等信息

2、通过multipart/form-data类型数据实现上传文件

具体实现

static String STR = "{\"name\":\"%s\",\"metaData\":{\"_name\":\"%s\",\"size\":%d,\"_checksum\":\"%s\"}}}";

String str = String.format(STR, "playlist180.m3u8", "playlist180.m3u8", 123, "d0e2a6be565e57c7a3c44848feb2911f");
System.out.println(str);
postRequest("https://xxxxx/1.1/fileTokens", str, "POST");

 通过以上方法可获得结果 

{"upload_url":"https://upload.qiniup.com",
"mime_type":"application/vnd.apple.mpegurl",
"key":"xxx",
"objectId":"xxx",
"createdAt":"2024-0901:13:57.011Z",
"token":"xxx","url":"xxx","provider":"qiniu","bucket":"xxx"}

然后继续调用

FileUtils.uploadFile(data, upload_url, key, token);

上传到七牛云即可。

关键方法

/**
     * post请求
     */
private static void postRequest(String postUrl, String s, String method) {
        InputStream inputstream = null;
        try {
            URL url = new URL(postUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.addRequestProperty("X-LC-Id", "xxx");
            connection.addRequestProperty("X-LC-Key", "xxx,master");
            connection.addRequestProperty("Content-Type", "application/json");
            connection.setRequestMethod(method);
            connection.setConnectTimeout(500);
            connection.setReadTimeout(1000);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(s.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();

            connection.connect();
            System.out.println("[" + method + "]" + postUrl);
            if (connection.getResponseCode() == 200 || connection.getResponseCode() == 201) {
                inputstream = connection.getInputStream();
                int bufferSize = 1024;
                char[] buffer = new char[bufferSize];
                StringBuilder out = new StringBuilder();
                Reader in = new InputStreamReader(inputstream, StandardCharsets.UTF_8);
                for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {
                    out.append(buffer, 0, numRead);
                }
                System.out.println(out.toString());
            } else if(connection.getResponseCode() == 400) {
                inputstream = connection.getErrorStream();
                int bufferSize2 = 1024;
                char[] buffer = new char[bufferSize2];
                StringBuilder out2 = new StringBuilder();
                Reader in = new InputStreamReader(inputstream, StandardCharsets.UTF_8);
                for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {
                    out2.append(buffer, 0, numRead);
                }
                System.out.println(out2.toString());
            }else{
                System.out.println("Post error code " + connection.getResponseCode());
            }
        } catch (IOException e) {
        } finally {
            try {
                if (inputstream != null) {
                    inputstream.close();
                }
            } catch (IOException e) {}
        }
    }
/**
     * 上传七牛云
     */
private static void uploadFile(byte[] data, String upload_url, String filename, String token) {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "-------------" + System.currentTimeMillis();

        DataOutputStream ds = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        try {
            // 统一资源
            URL url = new URL(upload_url);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            httpURLConnection.setDoInput(true);
            // 设置是否向httpUrlConnection输出
            httpURLConnection.setDoOutput(true);
            // Post 请求不能使用缓存
            httpURLConnection.setUseCaches(false);
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码连接参数
            //httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符编码
            //httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置请求内容类型
            //httpURLConnection.setRequestProperty("Authorization", "UpToken " + token);

            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            // 设置DataOutputStream
            ds = new DataOutputStream(httpURLConnection.getOutputStream());

            //封装键值对数据一
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; name=\"token\"");
            ds.writeBytes(end);
            ds.writeBytes(end);
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                ds.writeBytes(getToken(filename));
//            }
            ds.writeBytes(token);
            ds.writeBytes(end);


            //封装键值对数据三
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; name=\"key\"");
            ds.writeBytes(end);
            ds.writeBytes(end);
            ds.writeBytes(filename);
            ds.writeBytes(end);

            //封装图片数据
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename.substring(filename.lastIndexOf("/") + 1)
                    + "\"" + end);
            ds.writeBytes("Content-Type: " + "image/jpeg" + end);
            //ds.writeBytes("Content-Lenght: "+file.length()+ end);
            ds.writeBytes(end);
            int len = data.length;
            ds.write(data, 0, len);
            ds.writeBytes(end);
            //输入结束
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            /* close streams */
            ds.flush();

            if (httpURLConnection.getResponseCode() == 200) {
                inputStream = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                reader = new BufferedReader(inputStreamReader);
                tempLine = null;
                resultBuffer = new StringBuffer();
                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                    resultBuffer.append("\n");
                }
                System.out.println(resultBuffer);
            }else if (httpURLConnection.getResponseCode() == 400
                    || httpURLConnection.getResponseCode() == 401
                    || httpURLConnection.getResponseCode() == 403) {
                inputStream = httpURLConnection.getErrorStream();
                inputStreamReader = new InputStreamReader(inputStream);
                reader = new BufferedReader(inputStreamReader);
                tempLine = null;
                resultBuffer = new StringBuffer();
                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                    resultBuffer.append("\n");
                }
                System.out.println(resultBuffer);
            }else{
                System.out.println(httpURLConnection.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ds != null) {
                try {
                    ds.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值