首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Android -将图像上传到服务器的最佳实践

Android -将图像上传到服务器的最佳实践
EN

Stack Overflow用户
提问于 2019-06-25 04:47:59
回答 2查看 182关注 0票数 0

我有一些代码将字符串字节发送到服务器,然后在mvc c#中,我将这些字符串字节转换为原始字节,然后将这些字节保存到文件中。这很有效,但问题是,当我在HttpURLConnection中发送4个字符串字节的图像时,mvc服务器返回说文件未找到异常。

所以我发现,当我发送大图像时,它会失败,并出现此异常,而当我发送小于3080000字节的图像时,它会发送图像并将其保存到服务器。

因此,现在我决定向用户显示一条消息,显示一个关于文件限制的对话框,这样做好吗?

这是我的代码:

客户端

try {

            if (imgS!=null && imgS.size()>0) {
                for (int i = 0; i < imgS.size(); i++) {

                    if(i == 0){
                        image1 = Base64.encodeToString(imgS.get(i).bytes, Base64.DEFAULT);
                    }
                    if(i == 1){
                        image2 = Base64.encodeToString(imgS.get(i).bytes, Base64.DEFAULT);
                    }
                    if(i == 2){
                        image3 = Base64.encodeToString(imgS.get(i).bytes, Base64.DEFAULT);
                    }
                    if(i == 3){
                        image4 = Base64.encodeToString(imgS.get(i).bytes, Base64.DEFAULT);
                    }
                }
            }


            if (!isDelivered) {
                deliveredId = 2;
            }


            if (params[0] != null && (params[0].equals("0.00") || !params[0].equals(""))) {
                priceTmp = Double.valueOf(params[0]);
            }

            if (params[6] != null && (params[6].equals("0.00") || !params[6].equals(""))) {
                postageTmp = Double.valueOf(params[6]);
            }
            String responseText = "";

            SharedPreferences preferences = getActivity().getSharedPreferences(PREFERENCE, Context.MODE_PRIVATE);

            String json = String.format("{\"p_u_id\": \"%s\",\"price\": \"%.2f\"," +
                            "\"title\": \"%s\"" +
                            ",\"description\": \"%s\",\"category\": \"%d\",\"tags\": \"%s\"" +
                            ",\"image1\": \"%s\",\"image2\": \"%s\",\"image3\": \"%s\",\"image4\": \"%s\"" +
                            ",\"postcode\": \"%s\",\"postage\": \"%.2f\",\"isDelivered\": \"%d\"}",
                    preferences.getString("userId", "0"),
                    priceTmp,
                    params[1],
                    params[2],
                    selectedCategory,
                    params[4],
                    image1,
                    image2,
                    "",
                    "",
                    params[5],
                    postageTmp,
                    deliveredId
            );

            long b = image1.getBytes().length + image2.getBytes().length +image3.getBytes().length + image4.getBytes().length;
            if(b > 3080000){


                return "FileLimit";

            }else{


                URL url = new URL("http://xxx/Home/xxxx");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(10000);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");      // have tried without this
                conn.setRequestProperty("Content-Length", json.getBytes().length + "");
                conn.setDoOutput(true);

                OutputStream os = conn.getOutputStream();
                os.write(json.getBytes("UTF-8"));
                os.close();

                conn.connect();

                InputStream is = conn.getInputStream();
                //here we read and print the response send by server; assuming that response type is text/html (MIME Type)
                StringBuilder sb = new StringBuilder();
                int ch;
                //-1: end of stream
                while ((ch = is.read()) != -1) {
                    sb.append((char) ch);
                }
                responseText = sb.toString();

                conn.disconnect();
                JSONObject obj = new JSONObject(responseText);
                pid = obj.getInt("id");
                serverImage1 = obj.getString("image1");
                serverImage2 = obj.getString("image2");


                json = String.format("{\"p_id\": \"%d\",\"image1\": \"%s\"," +
                                "\"image2\": \"%s\",\"p_u_id\": \"%s\"}",
                        pid,
                        image3,
                        image4,
                        preferences.getString("userId", "0")

                );

                url = new URL("http://xxx/Home/xxxx");
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(10000);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");      // have tried without this
                conn.setRequestProperty("Content-Length", json.getBytes().length + "");
                conn.setDoOutput(true);

                os = conn.getOutputStream();
                os.write(json.getBytes("UTF-8"));
                os.close();

                conn.connect();

                is = conn.getInputStream();
                //here we read and print the response send by server; assuming that response type is text/html (MIME Type)
                sb = new StringBuilder();
                ch = 0;
                //-1: end of stream
                while ((ch = is.read()) != -1) {
                    sb.append((char) ch);
                }

                responseText = sb.toString();
                return responseText;
            }




        } catch (Exception e) {
            int i = 0;
        }

我在这里所做的是将前两个图像发送到服务器,然后在发送前两个图像之后发送下两个图像。这很有趣,因为如果我发送两张大的图片,服务器会再次返回一个异常。

那么,向用户显示一条关于文件限制的消息是好的吗?

而像shpock和Ebay这样的其他应用程序在允许多个文件上传时又是如何工作的呢?

我试过使用一些Android库,但毫无悬念。

想知道一种发送四个文件的最大值的方法,而不显示用户的文件限制,只需直接发送4个图像。

MVC

if(image.Length > 0)
        {

            byte[] bytes = Convert.FromBase64String(image);

            if (!System.IO.Directory.Exists(Server.MapPath("~/App_Data/products/" + uid)))
            {
                System.IO.Directory.CreateDirectory(Server.MapPath("~/App_Data/products/") + uid);
            }


            if (!System.IO.Directory.Exists(Server.MapPath("~/App_Data/products/" + uid + "/" + pid)))
            {
                System.IO.Directory.CreateDirectory(Server.MapPath("~/App_Data/products/") + uid + "/" + pid);
            }
            string path = Path.Combine(Server.MapPath("~/App_Data/products/" + uid + "/" + pid), guid + "" + ".jpg");

            System.IO.File.WriteAllBytes(path, bytes);
        }
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56743736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档