我正在发送一个HttpURLConnection请求到服务器并尝试发送一个文件。我可以从客户端发送文件,但不确定如何在服务器端解析它。
我的客户端代码如下.
private void createRequestInCHESS(String sRequestId, String sLastUpdated) {
String boundary = "xyz";
String crlf = "\r\n";
String twoHyphens = "--";
String attachmentName = "file";
String attachmentFileName = "testFile.xlsx";
try {
File file = new File("c:\\MFGREQ-7.xlsx");
URL url = new URL(chess.getMfgRequestURL() + "/createRequest");
HttpURLConnection httpConnecton = (HttpURLConnection) url.openConnection();
httpConnecton.setRequestMethod(REQUEST_METHOD_POST);
httpConnecton.setRequestProperty("Accept", "application/json");
httpConnecton.setRequestProperty("Cache-Control", "no-cache");
httpConnecton.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
httpConnecton.setRequestProperty("id", sRequestId);
httpConnecton.setRequestProperty("lastModified", sLastUpdated);
httpConnecton.setDoOutput(true);
DataOutputStream outStream = new DataOutputStream(httpConnecton.getOutputStream());
outStream.writeBytes(twoHyphens + boundary + crlf);
outStream.writeBytes("Content-Disposition: form-data; name=\"" +
attachmentName + "\";filename=\"" + attachmentFileName + "\"" + crlf);
outStream.writeBytes(crlf);
byte[] bytes = Files.readAllBytes(file.toPath());
outStream.write(bytes);
outStream.flush();
outStream.close();
getResponseString(httpConnecton);
} catch (MalformedURLException me) {
me.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
服务器端代码如下.我可以用什么来检索从请求发送的文件.
@POST
@Path("/createRequest")
public Response createRequest(@Context HttpServletRequest request) {
try(BufferedReader reader = new BufferedReader(
new InputStreamReader(request.getInputStream()))) {
StringBuilder sbPayload = new StringBuilder();
String sLine;
while ((sLine = reader.readLine()) != null) {
sbPayload.append(sLine);
sbPayload.append(System.lineSeparator());
}
String data = sbPayload.toString();
// how do i retrieve file here ?
}
1条答案
按热度按时间9lowa7mx1#
您确实不想自己解析它。
那你就写吧。
items是上传文件的列表。