簡體   English   中英

如何從 Struts2 中的 HttpServletRequest 檢索多部分/表單數據

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

我正在嘗試從客戶端 android 應用程序檢索發送請求中發送的數據,但不幸的是我沒有從請求中獲取多部分數據,代碼只返回null值。

客戶端代碼:選項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,所以現在我無法獲取上傳的文件。 如何解決從請求中獲取多部分數據?

我通過使用“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
}

這里的參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM