0

I'm trying to send the file through HttpUrlConnection method.

   URL url = new URL(SERVER_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);//Allow Inputs
                connection.setDoOutput(true);//Allow Outputs
                connection.setUseCaches(false);//Don't use a cached Copy
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("ENCTYPE", "multipart/form-data");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                connection.setRequestProperty("uploaded_file",selectedFilePath);

sending the file with dataOutputStream.

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

But Not sure How to handle this HttlUrlConnection and fileoutputstream on server side.

I'm not sure i'm doing correct but trying to get input stream with simple RequestMapping. This is my server side.

  @RequestMapping(value="/fileUploadPage")
   public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model,HttpServletRequest req) throws IOException {

      How to handle 'httpUrlconnection outputstream' in here?


}
kong kim
  • 29
  • 1
  • 4

1 Answers1

0

The code snippet in your question shows you are using spring. Spring has support for multipart file upload, check the documentation. After you configure a MultipartResolver, you can do:

@PostMapping("/form")
public String handleFormUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        byte[] bytes = file.getBytes();
        // store the bytes somewhere
        return "redirect:uploadSuccess";
    }

    return "redirect:uploadFailure";
}
Assen Kolov
  • 4,143
  • 2
  • 22
  • 32
  • in client side. I'm using DataOutputStream. is server did not have to use inputstream? – kong kim Jul 18 '17 at 13:33
  • Spring can do that for you and give you a `MultipartFile` ready to use, so you don't have to handle lower level details. – Assen Kolov Jul 18 '17 at 13:36
  • i'm sending the DataoutputStream from native Android. am I suppose to use the dataoutputStream still in android to send image or File right? – kong kim Jul 18 '17 at 14:23
  • The server doesn't care or know for sure if the bytes that come in were sent with Android or Visual Basic or Haskell - they look all the same. – Assen Kolov Jul 18 '17 at 14:27
  • it does not response with @RequestParam("file") MultipartFile file. request mapping only response when I put @Validated FileModel file – kong kim Jul 19 '17 at 13:20