java—如何在struts2中从httpservletrequest检索多部分/表单数据

of1yzvn4  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(481)

我试图从客户端android应用程序检索post请求时发送的数据,但不幸的是,我没有从请求中获取多部分数据,代码只是返回 null 价值观。
客户端code:option 1:

private String uploadFile(String filePath) {
    Log.d(TAG, "uploadFile: called");
    HttpURLConnection connection;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1024 * 1024;

    File uploadFile = new File(filePath);

    if(!uploadFile.isFile()) {
        mDownloadStatus = DownloadStatus.NOT_INITIALIZED;
        Log.d(TAG, "uploadFile: file not found");
        return null;
    }
    try {
        FileInputStream fileInputStream = new FileInputStream(uploadFile);
        mDownloadStatus = DownloadStatus.PROCESSING;
        URL url = new URL(POSTUPLOADFILE_URL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setReadTimeout(10000);
        connection.setConnectTimeout(15000);
        connection.setRequestProperty("ENCTYPE", "multipart/form-data");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        connection.setRequestProperty("uploaded_file", filePath);
        connection.connect();

        dos = new DataOutputStream(connection.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ filePath + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        Log.d(TAG, "uploadFile: bytesAvailable: " + bytesAvailable);
        Log.d(TAG, "uploadFile: initial available: " + bytesAvailable);

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        Log.d(TAG, "uploadFile: initial: " + bytesRead);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            Log.d(TAG, "uploadFile: bytesRead: " + bytesRead);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        int responseCode = connection.getResponseCode();
        Log.d(TAG, "uploadFile: respnse code: " + responseCode);
        fileInputStream.close();
        dos.flush();
        dos.close();

        // receive upload link from server
        int ch;
        StringBuilder sb = new StringBuilder();
        InputStream is = connection.getInputStream();
        while ((ch = is.read()) != -1) {
            sb.append((char)ch);
        }
        is.close();
        mDownloadStatus = DownloadStatus.OK;

        return sb.toString();

    } catch (IOException e) {
        Log.e(TAG, "uploadFile: IOException: " + e);
    }

    mDownloadStatus = DownloadStatus.FAILED_OR_EMPTY;
    return null;
}

客户端代码:选项2:

private String uploadFile(String filePath) {
        File uploadFile = new File(filePath);

    if(!uploadFile.isFile()) {
        mDownloadStatus = DownloadStatus.NOT_INITIALIZED;
        Log.d(TAG, "uploadFile: file not found");
        return null;
    }

    try {
        mDownloadStatus = DownloadStatus.PROCESSING;
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(POSTUPLOADFILE_URL);
        FileBody fileBody = new FileBody(new File(filePath));
        StringBody title = new StringBody("Filename: " + filePath, ContentType.DEFAULT_TEXT);
        StringBody description = new StringBody("This is a post file", ContentType.DEFAULT_TEXT);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart("file", fileBody);
        builder.addPart("title", title);
        builder.addPart("description", description);
        HttpEntity entity = builder.build();

        post.setEntity(entity);

        Log.d(TAG, "uploadFile: executing request: ");
        HttpResponse response = httpClient.execute(post);
        Log.d(TAG, "uploadFile: response status: " + response.getCode());

        Log.d(TAG, "uploadFile: " + response.toString());
    } catch (IOException e) {
        Log.e(TAG, "uploadFile: IOException" + e.getMessage(), e);
    }

    mDownloadStatus = DownloadStatus.FAILED_OR_EMPTY;
    return null;
}

服务器端代码:

public String uploadFile() throws IOException, ServletException, FileUploadException {
    System.out.println("upload file on postAction: called");

    HttpServletRequest request = ServletActionContext.getRequest();
    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

    System.out.println("items size: " + items.size());

    for(FileItem item: items) {
        if(item.isFormField()) {
            // get file 
        } else {

        }
    }

    return null;

}

问题:请求中有多部分数据,因为 request.contentLength 是合理的大小,但列表大小只返回0,所以现在我无法获得上传的文件。如何解决从请求中获取多部分数据的问题?

oewdyzsn

oewdyzsn1#

我通过使用“multipartrequestwrapper”找到了问题的解决方案

public String uploadFile() throws IOException, ServletException, FileUploadException {
    System.out.println("upload file on postAction: called");

    HttpServletRequest request = ServletActionContext.getRequest();

    MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest());

    Enumeration<String> fileParameterNames = multipartRequest.getFileParameterNames();
    if(fileParameterNames.hasMoreElements()) {
           String inputValue = fileParameterNames.nextElement();
           System.out.println("inputValue: " + inputValue);
           String[] localFileNames = multipartRequest.getFileNames(inputValue);
           for (String fn : localFileNames) {
             System.out.println("local filename = " + fn);                   
           }
           File[] files = multipartRequest.getFiles(inputValue);
           for (File cf : files) {
             File destFile = new File(POST_FILE_DESTINATION + localFileNames[0]);
             FileUtils.copyFile(cf, destFile);
             FileUtils.deleteQuietly(cf);
           }               
     }
        return null
}

此处引用

相关问题