Android基礎之文件上傳

public class FileUploader extends Thread {
    /**
     * 超時時間
     */
    public static final int IWP_HTPPCIIENT_TIMEOUT = 60;
    public static final int IWP_HTPPCIIENT_SO_TIMEOUT = 60;

    private File file;
    private OnFileUploadListener listener;

    /**
     * 文件上傳
     *
     * @param file     需要上傳的文件
     * @param listener 文件上傳結果監聽
     */
    public FileUploader(@NonNull File file, @NonNull OnFileUploadListener listener) {
        this.file = file;
        this.listener = listener;
    }

    /**
     * 回調結果到主線程
     */
    private void notifyResult(final boolean isSuccess, final String data) {
        App.getHandler().post(new Runnable() {
            @Override
            public void run() {
                listener.onUploadFinish(isSuccess, data);
            }
        });
    }

    public String getParams() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("file_size", file.length());
            jsonObject.put("file_name", file.getName());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    public void run() {
        boolean isSuccess = false;
        String data = null;
        try {
            JSONObject jsonObject = sendFileToServer("", file.getAbsolutePath(), new JSONObject(getParams()));
            if (jsonObject != null) {
                int code = jsonObject.getInt("code");
                if (code == 0) {
                    data = jsonObject.getString("file_name");
                    isSuccess = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        notifyResult(isSuccess, data);
    }

    /**
     * 文件上傳結果監聽
     */
    public interface OnFileUploadListener {
        /**
         * 文件上傳結果回調
         *
         * @param isSuccess 文件上傳是否成功,true:成功
         * @param data      文件上傳成功後,服務器返回的文件ID
         */
        void onUploadFinish(boolean isSuccess, @Nullable String data);
    }


    public static JSONObject sendFileToServer(String uploadFile, JSONObject jsonObject) throws IOException, JSONException {
        if (uploadFile == null || uploadFile.length() <= 0)
            return null;

        HttpURLConnection conn = null;
        try {
            String strUrl = Config.fileUpLoadUrl + "?json=" + jsonObject;

            if (BuildConfig.DEBUG)
                Log.d(TAG, "sendFileToServer: URL" + strUrl);

            URL uri = new URL(strUrl);
            conn = (HttpURLConnection) uri.openConnection();
            conn.setConnectTimeout(IWP_HTPPCIIENT_TIMEOUT * 1000);
            conn.setReadTimeout(IWP_HTPPCIIENT_SO_TIMEOUT * 1000);
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Live");//設置請求頭屬性
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("Accept-Encoding", "gzip");

            DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());

            FileInputStream fStream = new FileInputStream(uploadFile);
            byte[] fileByte = new byte[1024];
            int length = -1;
            while ((length = fStream.read(fileByte)) != -1) {
                outStream.write(fileByte, 0, length);
            }
            fStream.close();
            outStream.flush();
            outStream.close();
            JSONObject reJsonObject = null;
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                String m_strResult = null;
                InputStream iStream = null;
                iStream = conn.getInputStream();
                String m_strContentEncoding = conn.getContentEncoding();
                if (m_strContentEncoding != null && m_strContentEncoding.contains("gzip")) {
                    GZIPInputStream gzipIs = new GZIPInputStream(iStream);
                    m_strResult = FileUtils.getStringBySream(gzipIs);
                } else {
                    m_strResult = FileUtils.getStringBySream(iStream);
                }
                reJsonObject = new JSONObject(m_strResult);
            }
            return reJsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null)
                conn.disconnect();
        }
        return null;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章