我如何在java中解析从multipart/form-data请求发送来的内容以获取文件?

eqqqjvef  于 2023-01-19  发布在  Java
关注(0)|答案(1)|浏览(212)

我正在发送一个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 ?

}
9lowa7mx

9lowa7mx1#

您确实不想自己解析它。
那你就写吧。

DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8"); // Might be needed, depending on exact setup.
java.util.List<FileItem> items = upload.parseRequest(request);

items是上传文件的列表。

相关问题