浏览代码

上传文件

ltt 1 年之前
父节点
当前提交
d0289c2c8f

+ 27 - 2
TMessagesProj/src/main/java/org/telegram/cricdit/mvp/SendAnFeedPresenter.java

@@ -7,11 +7,15 @@ import org.telegram.cricdit.bean.RankListBean;
 import org.telegram.cricdit.net.ApiService;
 import org.telegram.cricdit.net.Parameter;
 import org.telegram.cricdit.utils.ParamsUtil;
-import org.telegram.messenger.R;
 
+import java.io.File;
 import java.util.ArrayList;
 import java.util.List;
 
+import okhttp3.MediaType;
+import okhttp3.MultipartBody;
+import okhttp3.RequestBody;
+
 
 public class SendAnFeedPresenter extends BasePresenter<SendAnFeedView> {
 
@@ -37,7 +41,7 @@ public class SendAnFeedPresenter extends BasePresenter<SendAnFeedView> {
             public void onError(Throwable e) {
                 super.onError(e);
                 if(getView()!=null){
-                    getView().showResult(1);
+                    getView().showErrorImg(e);
                 }
             }
         });
@@ -64,4 +68,25 @@ public class SendAnFeedPresenter extends BasePresenter<SendAnFeedView> {
             }
         });
     }
+
+    public void uploadFile(File file,boolean isVideo){
+        RequestBody body = RequestBody.create(MediaType.parse(isVideo?"image/*":"video/*"), file);
+        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), body);
+        addSubscribe(create(ApiService.class).uploadFile(part), new BaseObserver<String>() {
+            @Override
+            protected void onSuccess(String data) {
+                if(getView()!=null){
+                    getView().getImgUrl(data);
+                }
+            }
+
+            @Override
+            public void onError(Throwable e) {
+                if(getView()!=null){
+                    getView().showErrorImg(e);
+                }
+                super.onError(e);
+            }
+        });
+    }
 }

+ 2 - 0
TMessagesProj/src/main/java/org/telegram/cricdit/mvp/SendAnFeedView.java

@@ -9,4 +9,6 @@ public interface SendAnFeedView extends IView {
     void showResult(int code);
     void showTagList(List<String> list);
     String getUid();
+    void getImgUrl(String url);
+    void showErrorImg(Throwable e);
 }

+ 8 - 2
TMessagesProj/src/main/java/org/telegram/cricdit/net/ApiService.java

@@ -11,17 +11,18 @@ import org.telegram.cricdit.bean.NewsSearchWordBean;
 import org.telegram.cricdit.bean.NewsTagBean;
 import org.telegram.cricdit.bean.RankListBean;
 import org.telegram.cricdit.bean.RankDetailBean;
-import org.telegram.cricdit.bean.UpdateBean;
 import org.telegram.cricdit.bean.ReplyBean;
 import org.telegram.cricdit.config.Constants;
 
 import io.reactivex.Observable;
+import okhttp3.MultipartBody;
 import okhttp3.RequestBody;
 import okhttp3.ResponseBody;
 import retrofit2.Call;
-import retrofit2.Response;
 import retrofit2.http.Body;
+import retrofit2.http.Multipart;
 import retrofit2.http.POST;
+import retrofit2.http.Part;
 
 /**
  * 所有Cricdit请求接口存放位置
@@ -115,4 +116,9 @@ public interface ApiService {
     @POST(Constants.APP_AUTH_URL + "/user/followme")
     Call<ResponseBody> getFollowMe(@Body RequestBody requestBody);
 
+    //上传文件
+    @Multipart
+    @POST(Constants.APP_AUTH_URL + "/demo/upload")
+    Observable<BaseResponse<String>> uploadFile(@Part MultipartBody.Part body);
+
 }

+ 79 - 120
TMessagesProj/src/main/java/org/telegram/cricdit/ui/SendAnFeedActivity.java

@@ -67,6 +67,7 @@ import com.zhy.view.flowlayout.TagFlowLayout;
 
 import org.telegram.cricdit.bean.NewsMsgEvent;
 import org.telegram.cricdit.utils.EventBusHelper;
+import org.telegram.cricdit.utils.FileUtils;
 import org.telegram.cricdit.view.pictureselect.FullyGridLayoutManager;
 import org.telegram.cricdit.adapter.PictureAdapter;
 import org.telegram.cricdit.base.BaseActivity;
@@ -82,8 +83,10 @@ import org.telegram.messenger.UserConfig;
 import org.telegram.ui.ActionBar.ActionBarMenu;
 import org.telegram.ui.ActionBar.ActionBarMenuItem;
 import org.telegram.ui.ActionBar.AlertDialog;
+import org.telegram.ui.ActionBar.BaseFragment;
 
 import java.io.File;
+import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -119,11 +122,9 @@ public class SendAnFeedActivity extends BaseActivity<SendAnFeedPresenter> implem
     private int maxSelectNum = 9,maxSelectVideoNum = 1;
     private static final int CHOOSE_REQUEST = 1000;
     private int pageSize = 10,page = 1,offset=0;
-    private final Handler mHandler = new Handler() {
-        @SuppressLint("HandlerLeak")
+    private final Handler mHandler = new Handler(new Handler.Callback() {
         @Override
-        public void handleMessage(@NonNull Message msg) {
-            super.handleMessage(msg);
+        public boolean handleMessage(Message msg) {
             if(msg.what == 1){
                 //发布动态-图片
                 String str = edit.getText().toString();
@@ -132,16 +133,24 @@ public class SendAnFeedActivity extends BaseActivity<SendAnFeedPresenter> implem
             }else if(msg.what == 2){
                 //有图片/视频上传失败
                 dialog.dismiss();
-                ToastUtil.show(mContext,LocaleController.getString("please_try_again", R.string.send_news_char_short_info));
+                ToastUtil.show(mContext,LocaleController.getString(R.string.please_try_again));
                 mImages.clear();
+//                finishFragment();
             }else if(msg.what == 3){
                 //发布动态-视频
                 String str = edit.getText().toString();
                 presenter.publicNews(str, mImages, selectTags.toArray(new String[selectTags.size()]),true);
                 mImages.clear();
+            }else if(msg.what == 4){
+                //超过大小
+                if(localMediaList.size() == 0){
+                    dialog.dismiss();
+                }
+                ToastUtil.show(mContext,LocaleController.getString(R.string.post_resource_size_tip));
             }
+            return false;
         }
-    };
+    });
 
     @Override
     protected void initView(View v) {
@@ -300,7 +309,7 @@ public class SendAnFeedActivity extends BaseActivity<SendAnFeedPresenter> implem
                 selectionModel.forResult(CHOOSE_REQUEST);
             }
         });
-        //话题
+
         tvChooseTag.setOnClickListener((view -> {
             if(offset<=0){
                 presenter.getTagList(pageSize,page);
@@ -311,14 +320,10 @@ public class SendAnFeedActivity extends BaseActivity<SendAnFeedPresenter> implem
 
         edit.addTextChangedListener(new TextWatcher() {
             @Override
-            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
-
-            }
+            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
 
             @Override
-            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
-
-            }
+            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
 
             @Override
             public void afterTextChanged(Editable editable) {
@@ -381,65 +386,40 @@ public class SendAnFeedActivity extends BaseActivity<SendAnFeedPresenter> implem
         rvTags.setAdapter(tagsArrayAdapter);
         tagPopupView.setBackgroundColor(ColorUtil.COLOR_WHITE);
         smartRefreshLayout.setEnableRefresh(false);
-        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
-            @Override
-            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
-                smartRefreshLayout.finishLoadMore();
-                if (tagsArrayAdapter.getCount() == page * pageSize) {
-                    page++;
-                    presenter.getTagList(pageSize, page);
-                    offset = page * pageSize;
-                }
-            }
-        });
-
-        mTagPopupWindow = new PopupWindow(tagPopupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
-        mTagPopupWindow.setAnimationStyle(R.style.PopupAnimation);
-        mTagPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
-            @Override
-            public void onDismiss() {
-                backgroundAlpha(1.0f);
+        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
+            smartRefreshLayout.finishLoadMore();
+            if (tagsArrayAdapter.getCount() == page * pageSize) {
+                page++;
+                presenter.getTagList(pageSize, page);
+                offset = page * pageSize;
             }
         });
 
-        rvTags.setOnItemClickListener(new AdapterView.OnItemClickListener() {
-            @Override
-            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
-                String str = showTags.get(i);
-                if(selectTags.size()>4){
-                    ToastUtil.show(mContext,String.format(LocaleController.getString("news_post_tags_maximum", R.string.news_post_tags_maximum),"5"));
-                }else if(!selectTags.contains(showTags.get(i))){
-                    selectTags.add(0, str);
-                    selTagAdapter.notifyDataChanged();
-                }
-                mTagPopupWindow.dismiss();
-            }
-        });
-
-        mTagPopupWindow.setTouchable(true);
-        mTagPopupWindow.setFocusable(true);
-        mTagPopupWindow.setOutsideTouchable(false);
         if(mTagPopupWindow == null){
             mTagPopupWindow = new PopupWindow(tagPopupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
+            mTagPopupWindow.setAnimationStyle(R.style.PopupAnimation);
+            mTagPopupWindow.setOnDismissListener(() -> backgroundAlpha(1.0f));
+            mTagPopupWindow.setTouchable(true);
+            mTagPopupWindow.setFocusable(true);
+            mTagPopupWindow.setOutsideTouchable(false);
         }
-
-        mTagPopupWindow.setAnimationStyle(R.style.PopupAnimation);
-        mTagPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
-            @Override
-            public void onDismiss() {
-                backgroundAlpha(1.0f);
+        rvTags.setOnItemClickListener((adapterView, view, i, l) -> {
+            String str = showTags.get(i);
+            if(selectTags.size()>4){
+                ToastUtil.show(mContext,String.format(LocaleController.getString(R.string.news_post_tags_maximum),"5"));
+            }else if(!selectTags.contains(showTags.get(i))){
+                selectTags.add(0, str);
+                selTagAdapter.notifyDataChanged();
             }
+            mTagPopupWindow.dismiss();
         });
-        mTagPopupWindow.setTouchable(true);
-        mTagPopupWindow.setFocusable(true);
-        mTagPopupWindow.setOutsideTouchable(false);
     }
 
     @Override
     public void showResult(int result) {
         EventBusHelper.post(new NewsMsgEvent("feed"));
         dialog.dismiss();
-        ToastUtil.show(mContext,(result == 0)?LocaleController.getString("submit_success", R.string.submit_success):LocaleController.getString("submit_success", R.string.submit_error));
+        ToastUtil.show(mContext,(result == 0)?LocaleController.getString(R.string.submit_success):LocaleController.getString(R.string.submit_error));
         finishFragment();
     }
 
@@ -476,91 +456,70 @@ public class SendAnFeedActivity extends BaseActivity<SendAnFeedPresenter> implem
             hideKeyboard(edit);
             String string = edit.getText().toString();
             if (TextUtils.isEmpty(string) || string.length() < 20) {
-                ToastUtil.show(mContext, LocaleController.getString("send_news_char_short_info", R.string.send_news_char_short_info));
+                ToastUtil.show(mContext, LocaleController.getString(R.string.send_news_char_short_info));
                 return;
             }
             if(isFastClick()){
                 dialog.show();
-//                ThreadPoolUtil.execute(() ->{
-                    /*localMediaList = pictureAdapter.getData();
+                    localMediaList = pictureAdapter.getData();
                     if(localMediaList.size() > 0){
-                        String fileVideoPath = localMediaList.get(0).getRealPath();
+                         String fileVideoPath = localMediaList.get(0).getRealPath();
                         if(PictureMimeType.isHasVideo(localMediaList.get(0).getMimeType()) && (!TextUtils.isEmpty(fileVideoPath))){
-                            //fixme ltt 上传文件接口
-                            OpenIMClient.getInstance().uploadFile(new OnFileUploadProgressListener() {
-                                @Override
-                                public void onError(int code, String error) {
-                                    Message message = new Message();
-                                    message.what = 2;
-                                    mHandler.sendMessage(message);
-                                }
-
-                                @Override
-                                public void onProgress(long progress) {}
-
-                                @Override
-                                public void onSuccess(String s) {
-                                    if(!TextUtils.isEmpty(s)){
-                                        mImages.add(s);
-                                    }
-                                    if(mImages.size() == localMediaList.size()){
-                                        Message message = new Message();
-                                        message.what = 3;
-                                        mHandler.sendMessage(message);
-                                    }
+                            if(FileUtils.getAutoFileOrFilesSize(fileVideoPath,FILE_SPECIFY_SIZE)){
+                                localMediaList.remove(0);
+                                Message message = new Message();
+                                message.what = 4;
+                                mHandler.sendMessage(message);
+                            }else{
+                                if (!TextUtils.isEmpty(fileVideoPath)) {
+                                    presenter.uploadFile(new File(fileVideoPath),true);
                                 }
-                            }, fileVideoPath);
+                            }
                         }else{
-                            //上传图片
                             for (LocalMedia media :localMediaList) {
                                 String filePath = media.getRealPath();
-                            if(FileUtils.getAutoFileOrFilesSize(media.getRealPath(),2097152)){
-                                localMediaList.remove(media);
-                                Message message = new Message();
-                                message.what = 3;
-                                mHandler.sendMessage(message);
-                                continue;
-                            }
+                                if(FileUtils.getAutoFileOrFilesSize(filePath,FILE_SPECIFY_SIZE)){
+                                    localMediaList.remove(media);
+                                    Message message = new Message();
+                                    message.what = 4;
+                                    mHandler.sendMessage(message);
+                                    continue;
+                                }
 
                                 if (!TextUtils.isEmpty(filePath)) {
-                                    //上传图片接口
-                                    OpenIMClient.getInstance().uploadFile(new OnFileUploadProgressListener() {
-                                        @Override
-                                        public void onError(int code, String error) {
-                                            Message message = new Message();
-                                            message.what = 2;
-                                            mHandler.sendMessage(message);
-                                        }
-
-                                        @Override
-                                        public void onProgress(long progress) {}
-
-                                        @Override
-                                        public void onSuccess(String s) {
-                                            if(!TextUtils.isEmpty(s)){
-                                                mImages.add(s);
-                                            }
-                                            if(mImages.size() == localMediaList.size()){
-                                                Message message = new Message();
-                                                message.what = 1;
-                                                mHandler.sendMessage(message);
-                                            }
-                                        }
-                                    }, filePath);
+                                    presenter.uploadFile(new File(filePath),false);
                                 }
                             }
                         }
-                    }else{*/
-                        //纯文字
+                    }else{
                         Message message = new Message();
                         message.what = 1;
                         mHandler.sendMessage(message);
-//                    }
+                    }
                 };
         });
     }
 
     @Override
+    public void getImgUrl(String url) {
+        if(!TextUtils.isEmpty(url)){
+            mImages.add(url);
+        }
+        if(mImages.size() == localMediaList.size()){
+            Message message = new Message();
+            message.what = 1;
+            mHandler.sendMessage(message);
+        }
+    }
+
+    @Override
+    public void showErrorImg(Throwable e) {
+        Message message = new Message();
+        message.what = 2;
+        mHandler.sendMessage(message);
+    }
+
+    @Override
     protected int getLayoutResId() {
         return R.layout.activity_send_an_feed;
     }

+ 220 - 0
TMessagesProj/src/main/java/org/telegram/cricdit/utils/FileUtils.java

@@ -0,0 +1,220 @@
+package org.telegram.cricdit.utils;
+
+import android.os.Environment;
+import android.text.TextUtils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.math.BigDecimal;
+import java.text.DecimalFormat;
+
+public class FileUtils {
+
+    public static boolean isSDCardAlive() {
+        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
+    }
+
+    public static void delete(File file, String except) {
+        if (file == null) {
+            return;
+        }
+        if (file.isDirectory()) {
+            String[] children = file.list();
+            for (String c : children) {
+                File childFile = new File(file, c);
+                if (!TextUtils.equals(childFile.getName(), except)) {
+                    delete(childFile);
+                }
+            }
+        } else {
+            if (!TextUtils.equals(file.getName(), except)) {
+                file.delete();
+            }
+        }
+    }
+
+    public static boolean delete(File file) {
+        if (file == null) {
+            return false;
+        }
+        if (file.isDirectory()) {
+            String[] children = file.list();
+            for (String c : children) {
+                boolean success = delete(new File(file, c));
+                if (!success) {
+                    return false;
+                }
+            }
+        }
+        return file.delete();
+    }
+
+    public static long getSize(File file) {
+        long size = 0;
+        try {
+            File[] fileList = file.listFiles();
+            for (File f : fileList) {
+                if (f.isDirectory()) {
+                    size = size + getSize(f);
+                } else {
+                    size = size + f.length();
+                }
+            }
+        } catch (Exception ignore) {
+        }
+        return size;
+    }
+
+    /**
+     * 调用此方法自动计算指定文件或指定文件夹的大小
+     *
+     * @param filePath 文件路径
+     * @return 计算好的带B、KB、MB、GB的字符串
+     */
+    public static String getAutoFileOrFilesSize(String filePath) {
+        File file = new File(filePath);
+        long blockSize = 0;
+        try {
+            if (file.isDirectory()) {
+                blockSize = getFileSizes(file);
+            } else {
+                blockSize = getFileSize(file);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return FormetFileSize(blockSize);
+    }
+
+    /**
+     * 调用此方法自动计算指定文件或指定文件夹的大小
+     *
+     * @param filePath 文件路径
+     * @return 计算好的带B、KB、MB、GB的字符串
+     */
+    public static long getAutoFileOrFilesSize(String filePath,boolean is) {
+        File file = new File(filePath);
+        long blockSize = 0;
+        try {
+            if (file.isDirectory()) {
+                blockSize = getFileSizes(file);
+            } else {
+                blockSize = getFileSize(file);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return blockSize;
+    }
+
+    /**
+     * 计算文件是否超过指定大小
+     */
+    public static boolean getAutoFileOrFilesSize(String filePath, long specifySize) {
+        File file = new File(filePath);
+        long blockSize = 0;
+        try {
+            if (file.isDirectory()) {
+                blockSize = getFileSizes(file);
+            } else {
+                blockSize = getFileSize(file);
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            return false;
+        }
+        return blockSize > specifySize;
+    }
+
+
+    /**
+     * 获取指定文件大小
+     *
+     * @param file
+     * @return
+     * @throws Exception
+     */
+    private static long getFileSize(File file) throws Exception {
+        long size = 0;
+        if (file.exists()) {
+            FileInputStream fis = null;
+            fis = new FileInputStream(file);
+            size = fis.available();
+        } else {
+            file.createNewFile();
+        }
+        return size;
+    }
+
+    /**
+     * 转换文件大小
+     *
+     * @param fileS
+     * @return
+     */
+    private static String FormetFileSize(long fileS) {
+        DecimalFormat df = new DecimalFormat("#.00");
+        String fileSizeString = "";
+        String wrongSize = "0B";
+        if (fileS == 0) {
+            return wrongSize;
+        }
+        if (fileS < 1024) {
+            fileSizeString = df.format((double) fileS) + "B";
+        } else if (fileS < 1048576) {
+            fileSizeString = df.format((double) fileS / 1024) + "KB";
+        } else if (fileS < 1073741824) {
+            fileSizeString = df.format((double) fileS / 1048576) + "MB";
+        } else {
+            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
+        }
+        return fileSizeString;
+    }
+
+    /**
+     * 获取指定文件夹
+     *
+     * @param f
+     * @return
+     * @throws Exception
+     */
+    private static long getFileSizes(File f) throws Exception {
+        long size = 0;
+        File flist[] = f.listFiles();
+        for (int i = 0; i < flist.length; i++) {
+            if (flist[i].isDirectory()) {
+                size = size + getFileSizes(flist[i]);
+            } else {
+                size = size + getFileSize(flist[i]);
+            }
+        }
+        return size;
+    }
+
+    /**
+     * 格式化单位
+     */
+    public static String formatSize(double size) {
+        double kiloByte = size / 1024;
+        if (kiloByte < 1) {
+            return "0KB";
+        }
+        double megaByte = kiloByte / 1024;
+        if (megaByte < 1) {
+            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
+            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
+        }
+        double gigaByte = megaByte / 1024;
+        if (gigaByte < 1) {
+            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
+            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
+        }
+        double teraBytes = gigaByte / 1024;
+        if (teraBytes < 1) {
+            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
+            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
+        }
+        BigDecimal result4 = new BigDecimal(teraBytes);
+        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
+    }
+}

+ 1 - 0
TMessagesProj/src/main/res/values/string-cricdit.xml

@@ -120,4 +120,5 @@
     <string name="financial_ranking">Financial ranking</string>
     <string name="send">Send</string>
     <string name="empty_tip">The content cannot be empty</string>
+    <string name="post_resource_size_tip">Description Failed to upload resources exceeding 10MB.</string>
 </resources>