【问题标题】:upload file using post method in android在android中使用post方法上传文件
【发布时间】:2014-02-13 16:41:43
【问题描述】:

我想将文件上传到 php 服务器。 我可以使用以下方法上传文件:

curl -i -X POST -F file=@1.jpg http://something/sth

然后我可以使用浏览器下载。

但是当使用下面的 java 代码上传文件时,我无法使用浏览器下载。

URL url = new URL(mUrl);
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        String Tag = "fSnd";
        Log.e(Tag, "Starting Http File Sending to URL");
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                bytes);
        // Open a HTTP connection to the URL
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // Allow Inputs
        conn.setDoInput(true);

        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Connection", "Keep-Alive");

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

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

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"title\""
                + lineEnd);
        dos.writeBytes(lineEnd);
        dos.writeBytes("File1");
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + lineEnd);

        dos.writeBytes("Content-Disposition: form-data; name=\"description\""
                + lineEnd);
        dos.writeBytes(lineEnd);
        dos.writeBytes("File2");
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + lineEnd);

        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                + "File3.jpg" + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        Log.e(Tag, "Headers are written");

        byte data[] = new byte[1024 * 2];
        int count = 0;
        while ((count = byteArrayInputStream.read(data)) != -1) {
            mSoFarLength += count;
            Log.d("FFF", "count : " + count + " mSoFarLength : "
                    + mSoFarLength + " mTotalLength : " + mTotalLength);
            dos.write(data, 0, count);
            mProgress = ((mSoFarLength * 100) / mTotalLength);
            for (LocalTransmitterListener baseTransmitterListener : baseTransmitterListeners) {
                baseTransmitterListener.onUpdateProgress(mProgress);
            }
        }

        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // close streams
        byteArrayInputStream.close();

        dos.flush();

        Log.e(Tag,
                "File Sent, Response: "
                        + String.valueOf(conn.getResponseCode()));

        InputStream is = conn.getInputStream();

        // retrieve the response from server
        int ch;

        StringBuffer b = new StringBuffer();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        String s = b.toString();
        Log.i("Response", s);
        dos.close();

【问题讨论】:

    标签: java android post file-upload upload


    【解决方案1】:

    这是我的上传代码,它可以工作。你需要导入httpmime jar
    PHP代码

    $uploads_dir = '/Library/WebServer/Documents/Upload/upload/'.$_FILES['userfile']['name'];
    if(is_uploaded_file($_FILES['userfile']['tmp_name'])) {
        echo $_POST["contentString"]."\n";
        echo  "File path = ".$uploads_dir;
        move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $uploads_dir);
    } else {
        echo "\n Upload Error";
        echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
        print_r($_FILES);
    

    java代码

    HttpClient client = new DefaultHttpClient();
    HttpPost postMethod = new HttpPost("http://localhost/Upload/index.php");
    
    File file = new File(filePath);
    
    MultipartEntity entity = new MultipartEntity();
    FileBody contentFile = new FileBody(file);
    entity.addPart("userfile",contentFile);
    
    StringBody contentString = new StringBody("This is contentString");
    entity.addPart("contentString",contentString);
    
    postMethod.setEntity(entity);
    HttpResponse response = client.execute(postMethod);
    HttpEntity httpEntity = response.getEntity();
    String state = EntityUtils.toString(httpEntity);
    

    【讨论】:

    • 我需要上传进度条。感谢您的代码,但在 java 上传部分我可以在哪里上传我的进度数据?谢谢
    【解决方案2】:

    至少我找到了解决方案。我应该注意实体名称。它应该与服务器相同。

                DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(mUrl);
            File file = new File(mFileAdrress);
            FileInputStream fileInputStream = new FileInputStream(file);
            httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
                    System.getProperty("http.agent"));
            InputStreamBody inputStreamBody = new InputStreamBody(
                    fileInputStream, file.getName());
    
            MultipartEntityBuilder multipartEntity = MultipartEntityBuilder
                    .create();
            multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntity.addPart("file", inputStreamBody); // file should be same as server
            final HttpEntity myEntity = multipartEntity.build();
            class ProgressiveEntity implements HttpEntity {
                @Override
                public void consumeContent() throws IOException {
                    myEntity.consumeContent();
                }
    
                @Override
                public InputStream getContent() throws IOException,
                        IllegalStateException {
                    return myEntity.getContent();
                }
    
                @Override
                public Header getContentEncoding() {
                    return myEntity.getContentEncoding();
                }
    
                @Override
                public long getContentLength() {
                    return myEntity.getContentLength();
                }
    
                @Override
                public Header getContentType() {
                    return myEntity.getContentType();
                }
    
                @Override
                public boolean isChunked() {
                    return myEntity.isChunked();
                }
    
                @Override
                public boolean isRepeatable() {
                    return myEntity.isRepeatable();
                }
    
                @Override
                public boolean isStreaming() {
                    return myEntity.isStreaming();
                }
    
                @Override
                public void writeTo(OutputStream outstream) throws IOException {
    
                    class ProxyOutputStream extends FilterOutputStream {
    
                        public ProxyOutputStream(OutputStream proxy) {
                            super(proxy);
                        }
    
                        public void write(int idx) throws IOException {
                            out.write(idx);
                        }
    
                        public void write(byte[] bts) throws IOException {
                            out.write(bts);
                        }
    
                        public void write(byte[] bts, int st, int end)
                                throws IOException {
                            out.write(bts, st, end);
                        }
    
                        public void flush() throws IOException {
                            out.flush();
                        }
    
                        public void close() throws IOException {
                            out.close();
                        }
                    }
                    class ProgressiveOutputStream extends ProxyOutputStream {
                        public ProgressiveOutputStream(OutputStream proxy) {
                            super(proxy);
                        }
    
                        public void write(byte[] bts, int st, int end)
                                throws IOException {
                            writed += end;
                            out.write(bts, st, end);
                            mProgress = (int) ((mSoFarLength * 100) / (mTotalLength));
                        }
                    }
    
                    myEntity.writeTo(new ProgressiveOutputStream(outstream));
                }
    
            }
            ProgressiveEntity progressiveEntity = new ProgressiveEntity();
            httpPost.setEntity(progressiveEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String state = EntityUtils.toString(httpEntity);
    

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多