首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >连接关闭时,上传文件(超过2MB)在蓝莓边缘应用程序

连接关闭时,上传文件(超过2MB)在蓝莓边缘应用程序
EN

Stack Overflow用户
提问于 2014-05-29 23:49:40
回答 2查看 151关注 0票数 0

我试图上传文件从黑莓应用到亚马逊s3。

这是我的密码

代码语言:javascript
复制
  private synchronized void uploadFileToAmazon(CreateFileIdBean createFileIdBean)       throws UnsupportedEncodingException, IOException,ConnectionNotFoundException, ConnectionClosedException, BackupCancelledException, InterruptedException, BackupInterruptedException {

        String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";

        String Policy = "{\"expiration\": \"2020-12-01T12:00:00.000Z\","
                + "\"conditions\": ["
                + "{\"bucket\": \"" + BeanFactory.getUserCreateBackupidBean().getBucketName() + "\"},"
                + "{\"x-amz-security-token\": \"" + BeanFactory.getUserCreateBackupidBean().getAmazonToken() + "\"},"
                + "{\"success_action_status\": \"201\"},"
                + "[\"starts-with\", \"$Content-Type\", \"\"],"
                + "[\"starts-with\", \"$key\", \"" + BeanFactory.getUserCreateBackupidBean().getBackupPath() + "\"]"
                + "]"
                + "}";
        String encodePolicy = Base64.encode(Policy.getBytes());
        String signature = uploadSignature(Policy, BeanFactory.getUserCreateBackupidBean().getAmazonSecret());
        Hashtable params = new Hashtable();
        params.put("key", BeanFactory.getUserCreateBackupidBean().getBackupPath() + "/" + BeanFactory.getUserCreateFileIdBean().getFileId());
        params.put("AWSAccessKeyId", BeanFactory.getUserCreateBackupidBean().getAmazonKey());
        params.put("Content-Type", createFileIdBean.getFileTypeContent());
        params.put("x-amz-security-token", BeanFactory.getUserCreateBackupidBean().getAmazonToken());
        params.put("policy", encodePolicy);
        params.put("success_action_status", "201");
        params.put("Signature", signature);

        send(BOUNDARY, "http://" + BeanFactory.getUserCreateBackupidBean().getBucketName() + ".s3.amazonaws.com/", params, "file", BeanFactory.getUserCreateFileIdBean().getFileId(), createFileIdBean.getFileTypeContent(), createFileIdBean.getFileByte(), createFileIdBean);

    }

    private synchronized String getBoundaryMessage(String boundary, Hashtable params, String fileField, String fileName, String fileType, byte[] fileBytes, CreateFileIdBean createFileIdBean) {
        StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");

        Enumeration keys = params.keys();

        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            String value = (String) params.get(key);

            res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")
                    .append("\r\n").append(value).append("\r\n")
                    .append("--").append(boundary).append("\r\n");
        }

        return res.toString();
    }

    private synchronized void send(String boundarry, String url, Hashtable params, String fileField, String fileName, String fileType, byte[] fileBytes, CreateFileIdBean createFileIdBean) throws IOException,ConnectionClosedException,ConnectionNotFoundException, BackupCancelledException, InterruptedException, BackupInterruptedException {


            StringBuffer buffer = new StringBuffer();

            HttpConnection hc = null;
            InputStream is = null;
            InputStream inputFileDataStream = null;
            DataOutputStream dout = null;

            String boundary = boundarry;
            StringBuffer res = new StringBuffer();

            int ch;

            String boundaryMessage = getBoundaryMessage(boundary, params, fileField, fileName, fileType, fileBytes, createFileIdBean);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bos.write(boundaryMessage.getBytes());

            res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n")
                    .append("Content-Type: ").append(fileType).append("\r\n\r\n");

            bos.write(res.toString().getBytes());

            String end = "\r\n"+"--"+boundary+"\r\n"+"Content-Disposition: form-data; name=\""+"submit"+"\"\r\n"+"\r\n"+"Upload to Amazon S3"+"\r\n"+"--"+boundary+"--\r\n";

            try {

                    hc = (HttpConnection) Connector.open(url+Resources.getConnectionString(), Connector.READ_WRITE,true);
                    hc.setRequestMethod(HttpConnection.POST);
                    hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundarry);
                    hc.setRequestProperty("User-Agent", Resources.getUserAgentString());
                    //hc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
                    hc.setRequestProperty("Content-Language", "en-US");
                    hc.setRequestProperty("Connection", "Keep-Alive");
                    hc.setRequestProperty("Keep-Alive", "300");
                    hc.setRequestProperty("Expect", "100-continue");

                    hc.setRequestProperty("Content-Length", (bos.toByteArray().length+createFileIdBean.getFileSize()+end.getBytes().length)+"");
                    hc.setRequestProperty("Content-length", (bos.toByteArray().length+createFileIdBean.getFileSize()+end.getBytes().length)+"");

                    dout = new DataOutputStream(hc.openDataOutputStream());

                    dout.write(bos.toByteArray());


            inputFileDataStream = readInputStream(createFileIdBean.getFilePath());

                        while ((ch = inputFileDataStream.read()) != -1) {

            dout.write(ch);

            }   

                    dout.write(end.getBytes());

                    dout.flush();
                    //dout.close();


                    is = hc.openDataInputStream();

                    BeanFactory.getUserUploadFileBean().setResponseCode(hc.getResponseCode() + "");
                    BeanFactory.getUserUploadFileBean().setResponseMessage(hc.getResponseMessage());

                    while ((ch = is.read()) != -1) {

                        buffer.append((char) ch);
                    }

                    System.out.println("buffer"+buffer);

            } 
            catch (IOException e) {
                throw new BackupInterruptedException(Constants.ERROR_IN_UPLOAD);

            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (hc != null) {
                        hc.close();
                    }
                    if(inputFileDataStream !=null)
                    {
                        inputFileDataStream.close();
                    }
                    if(dout !=null)
                    {
                        dout.close();
                    }


                } catch (IOException e2) {
                    System.out.println("aa"+e2.getMessage());
                    throw e2;
                }
            }
    }

    private synchronized String uploadSignature(String policy, String secretKey) throws UnsupportedEncodingException {

        String encodePolciy = Base64.encode(policy.getBytes());
        HMac m = new HMac(new SHA1Digest());
        m.init(new KeyParameter(secretKey.getBytes("UTF-8")));
        byte[] bytes = encodePolciy.getBytes("UTF-8");
        m.update(bytes, 0, bytes.length);
        byte[] mac = new byte[m.getMacSize()];
        m.doFinal(mac, 0);
        String signature = Base64.encode(mac);
        return signature;
    }

   private synchronized InputStream readInputStream(String path) throws IOException {

        FileConnection fc = null;
        InputStream is = null;

        fc = (FileConnection) Connector.open(path.toString(), Connector.READ);
        if (!fc.exists()) {
            Settings.ERROR_MESSAGE = "File doesn't exist!";
            //throw new BackupInterruptedException(Settings.ERROR_MESSAGE);
        } else {
             is = fc.openInputStream();
        }
        if(fc !=null)
        {
            fc.close();
        }
        return is;
    }

在上传数据之后,当我试图获得响应代码(在BeanFactory.getUserUploadFileBean().setResponseCode(hc.getResponseCode() +“”;行中)时,它总是会得到连接关闭异常。对于小于2MB的文件,它可以正常工作。请帮帮我..。

EN

回答 2

Stack Overflow用户

发布于 2014-06-02 00:30:12

我使用HttpConnection的经验是,它总是在发送任何东西之前缓冲全部有效负载。对于BlackBerry曲线8520,16 up的数据最终导致设备无法使用。为此,我使用了一个原始的SocketConnection,并在我的应用程序中直接编写了HTTP部件,这样我就可以确保在字节击中套接字之前没有任何过度的缓冲。

我后来认识到的一个可能有用的方面是,在内置的HTTP-块对象中使用HttpConnection模式。由于HTTP块从根本上来说是一种流机制,因此它可能允许您退出默认情况下获得的“缓冲区全”逻辑。

票数 2
EN

Stack Overflow用户

发布于 2014-06-02 16:21:42

如果您试图传输大文件,您可能会得到可怕的HTTP错误413。如果内存正确,允许的最大文件大小在1到30 MB之间,这取决于传输类型(BIS、BES等)。

除此之外,还有一个内存配额可供应用程序使用。对于较旧的83XX模型,我们经验性地发现,应用程序的最大RAM大约为12 an。

但是,我们使用块连接(使用HTTP报头)成功地传输了大型文件,对于缓冲区,我们要么使用小数组(<< 12 MB),要么使用临时文件。

我将发布关于这个主题的经典链接:

如何使用BlackBerry移动数据系统下载大文件

什么是: HTTP 413请求实体太大

你可能会在BB论坛或其他网站上找到一些关于他们的东西。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23944875

复制
相关文章

相似问题

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