如何通过httpurlconnection发送图像

时间:2019-06-26 14:34:28

标签: android httpurlconnection


public void sendFile(File[] files) {
          httpURLConnection = (HttpURLConnection) url.openConnection();
          httpURLConnection.setUseCaches(false);
          httpURLConnection.setRequestMethod("POST");
          httpURLConnection.setDoOutput(true);
          httpURLConnection.setDoInput(true);
          httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
          httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
          httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=*****");
          BufferedOutputStream dos = new BufferedOutputStream(httpURLConnection.getOutputStream());

          dos.write("Content-Type: multipart/form-data; boundary=*****\r\n".getBytes());
          dos.write("Content-Transfer-Encoding: binary\r\n".getBytes());
          for (File file : files) {
            if(file.length() <= 0)
              continue;

            BufferedInputStream fileInput = new BufferedInputStream(new FileInputStream(file.getAbsoluteFile()));

            String what_is_here = String.format("Content-Disposition: form-data; name=\"files\"; filename=\"%s\"\r\n",
                    file.getAbsoluteFile());
            dos.write("--*****--\r\n".getBytes());
            dos.write(what_is_here.getBytes());
            dos.write("\r\n".getBytes());
            dos.flush();
            byte[] b = new byte[(int) file.length()];

            for (int i = 0; i < b.length; i++) {
              b[i] = (byte) fileInput.read();
            }

            dos.write(b);
            dos.write("\r\n".getBytes());
            dos.flush();
            fileInput.close();
          }
          dos.write("--*****--\r\n".getBytes());
          dos.flush();
          dos.close();
          Log.wtf("STATUS", httpURLConnection.getResponseCode() + "");
}

我的问题是这段代码有什么问题?我正在尝试将图像从平板电脑(android)发送到本地服务器(spring),但无法正常工作spring服务器无法看到正在发送的文件。

@PostMapping("/file")
  public void handleFileUpload(@RequestParam MultipartFile[] files) throws IOException {
    System.out.println("FILES: " + files.length);
  }

我正在使用这种方法来捕获文件,但是sysout打印的长度等于0;

当我通过邮递员对此方法进行调用时,它可以正常工作。因此,为什么我认为android应用有问题。请给我一些建议,因为我尝试了很多

0 个答案:

没有答案