你如何处理服务器端的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.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

但不确定如何在服务器端处理此 HttlUrlConnection 和文件输出流。

我不确定我做得是否正确,但试图获取输入流 简单的请求映射。这是我的服务器端。

@RequestMapping(value="/fileUploadPage")
public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model,HttpServletRequest req) throws IOException {
How to handle 'httpUrlconnection outputstream' in here?

}

问题中的代码片段显示您正在使用 spring。Spring 支持分段文件上传,请查看文档。配置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";
}

最新更新