你如何处理服务器端的HttpUrlConnection?

时间:2017-07-17 14:43:32

标签: java file http httpurlconnection dataoutputstream

我试图通过HttpUrlConnection方法发送文件。

   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);

使用dataOutputStream发送文件。

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

但不确定如何在服务器端处理此HttlUrlConnection和fileoutputstream。

我不确定我是否正确但尝试获取输入流 简单的RequestMapping。这是我的服务器端。

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

      How to handle 'httpUrlconnection outputstream' in here?


}

1 个答案:

答案 0 :(得分:0)

您问题中的代码段显示您正在使用spring。 Spring支持多部分文件上传,请检查documentation。配置MultipartResolver后,您可以执行以下操作:

@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";
}