简体   繁体   中英

How to retrieve multipart/form-data from HttpServletRequest in Struts2

I am trying to retrieve the sent data on post request from the client android app, but unfortunately i am not getting multipart data from request, the code just returns null value.

Client side 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;
}

client side code: option 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;
}

Server side code:

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;
    
}

PROBLEM: there is multipart data on the request,because request.contentLength is reasonable size, but list size just returns 0, so now I can't get uploaded file. How can I solve to get multipart data from the request?

I figured out the solution for the problem by using '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
}

the reference here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM