如何将图片(文件)上传到Android studio的服务器上?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (723)

我需要上传一张照片到服务器,我试过很多种方法,但什么也没有出来。

以下是我的代码:

URL url2 = new URL(url_for_loading_image);
conn = (HttpURLConnection) url2.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "token " + ClientToken);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

conn.setRequestProperty("Accept","application/json");
                    JSONObject jsonParam2 = new JSONObject();
jsonParam2.put("photo", getActivity().getExternalCacheDir()+"/saved.jpg");
jsonParam2.put("collect", "ddd");
jsonParam2.put("user_comment", "dsdsds");
Log.i("JSON", jsonParam2.toString());
DataOutputStream os2 = new DataOutputStream(conn.getOutputStream());
                    //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
                    os.writeBytes(jsonParam2.toString());

                    os2.flush();
                    os2.close();

<div class="form-group ">
  <label class="col-sm-2 control-label ">
      Фото чека
  </label>    
  <div class="col-sm-10">
    <input name="photo"  type="file"  value="" >    
  </div>
</div>
提问于
用户回答回答于

你需要在与服务器的连接中发送此RequestBody。

    return object : RequestBody() {

        override fun contentType() = return MediaType.parse("application/octet-stream")

        override fun writeTo(sink: BufferedSink?) {

            var bytes = ByteArray(length)

            while (file.available() > 0) {

                when (file) {
                    avaible >= length -> {
                        file.read(bytes, 0, length)
                        sink?.write(bytes)
                    } 
                    else -> {
                        bytes = ByteArray(file.available())
                        file.read(bytes, 0, file.available())
                        sink?.write(bytes)
                    }
                }   
            }    
        }
    }
用户回答回答于

下面是显示如何上传媒体文件的代码

/**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL, String charset)
            throws IOException {
        this.charset = charset;

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true);    // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
                true);
}

你需要向服务器发出两个请求,或者修改上面的代码,将json数据发送到多部分表单中。

扫码关注云+社区

领取腾讯云代金券