2017-07-17 36 views
0

我试图通过HttpUrlConnection方法发送文件。
你如何处理服务器端的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? 


} 
+0

没有'ENCTYPE'标头。 – SLaks

+0

你用什么语言开发服务器端?在PHP中,您可以使用$ _FILE – Mohsen

+0

访问多部分数据是否可以使用@Requestmapping处理文件输出流? –

回答

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"; 
} 
+0

在客户端。我正在使用DataOutputStream。服务器是不是必须使用inputstream? –

+0

Spring可以为你做到这一点,并给你一个'MultipartFile'准备好使用,所以你不必处理较低级别的细节。 –

+0

我从原生Android发送DataoutputStream。我想使用dataoutputStream仍然在Android发送图像或文件的权利? –