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

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

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

  1. private String uploadFile(String filePath) {
  2. Log.d(TAG, "uploadFile: called");
  3. HttpURLConnection connection;
  4. DataOutputStream dos = null;
  5. String lineEnd = "\r\n";
  6. String twoHyphens = "--";
  7. String boundary = "*****";
  8. int bytesRead, bytesAvailable, bufferSize;
  9. byte[] buffer;
  10. int maxBufferSize = 1024 * 1024;
  11. File uploadFile = new File(filePath);
  12. if(!uploadFile.isFile()) {
  13. mDownloadStatus = DownloadStatus.NOT_INITIALIZED;
  14. Log.d(TAG, "uploadFile: file not found");
  15. return null;
  16. }
  17. try {
  18. FileInputStream fileInputStream = new FileInputStream(uploadFile);
  19. mDownloadStatus = DownloadStatus.PROCESSING;
  20. URL url = new URL(POSTUPLOADFILE_URL);
  21. connection = (HttpURLConnection) url.openConnection();
  22. connection.setRequestMethod("POST");
  23. connection.setDoInput(true);
  24. connection.setDoOutput(true);
  25. connection.setUseCaches(false);
  26. connection.setReadTimeout(10000);
  27. connection.setConnectTimeout(15000);
  28. connection.setRequestProperty("ENCTYPE", "multipart/form-data");
  29. connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
  30. connection.setRequestProperty("uploaded_file", filePath);
  31. connection.connect();
  32. dos = new DataOutputStream(connection.getOutputStream());
  33. dos.writeBytes(twoHyphens + boundary + lineEnd);
  34. dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ filePath + "\"" + lineEnd);
  35. dos.writeBytes(lineEnd);
  36. bytesAvailable = fileInputStream.available();
  37. Log.d(TAG, "uploadFile: bytesAvailable: " + bytesAvailable);
  38. Log.d(TAG, "uploadFile: initial available: " + bytesAvailable);
  39. bufferSize = Math.min(bytesAvailable, maxBufferSize);
  40. buffer = new byte[bufferSize];
  41. // read file and write it into form...
  42. bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  43. Log.d(TAG, "uploadFile: initial: " + bytesRead);
  44. while (bytesRead > 0) {
  45. dos.write(buffer, 0, bufferSize);
  46. bytesAvailable = fileInputStream.available();
  47. bufferSize = Math.min(bytesAvailable, maxBufferSize);
  48. bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  49. Log.d(TAG, "uploadFile: bytesRead: " + bytesRead);
  50. }
  51. // send multipart form data necesssary after file data...
  52. dos.writeBytes(lineEnd);
  53. dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
  54. int responseCode = connection.getResponseCode();
  55. Log.d(TAG, "uploadFile: respnse code: " + responseCode);
  56. fileInputStream.close();
  57. dos.flush();
  58. dos.close();
  59. // receive upload link from server
  60. int ch;
  61. StringBuilder sb = new StringBuilder();
  62. InputStream is = connection.getInputStream();
  63. while ((ch = is.read()) != -1) {
  64. sb.append((char)ch);
  65. }
  66. is.close();
  67. mDownloadStatus = DownloadStatus.OK;
  68. return sb.toString();
  69. } catch (IOException e) {
  70. Log.e(TAG, "uploadFile: IOException: " + e);
  71. }
  72. mDownloadStatus = DownloadStatus.FAILED_OR_EMPTY;
  73. return null;
  74. }

客户端代码:选项2:

  1. private String uploadFile(String filePath) {
  2. File uploadFile = new File(filePath);
  3. if(!uploadFile.isFile()) {
  4. mDownloadStatus = DownloadStatus.NOT_INITIALIZED;
  5. Log.d(TAG, "uploadFile: file not found");
  6. return null;
  7. }
  8. try {
  9. mDownloadStatus = DownloadStatus.PROCESSING;
  10. HttpClient httpClient = HttpClients.createDefault();
  11. HttpPost post = new HttpPost(POSTUPLOADFILE_URL);
  12. FileBody fileBody = new FileBody(new File(filePath));
  13. StringBody title = new StringBody("Filename: " + filePath, ContentType.DEFAULT_TEXT);
  14. StringBody description = new StringBody("This is a post file", ContentType.DEFAULT_TEXT);
  15. MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  16. builder.addPart("file", fileBody);
  17. builder.addPart("title", title);
  18. builder.addPart("description", description);
  19. HttpEntity entity = builder.build();
  20. post.setEntity(entity);
  21. Log.d(TAG, "uploadFile: executing request: ");
  22. HttpResponse response = httpClient.execute(post);
  23. Log.d(TAG, "uploadFile: response status: " + response.getCode());
  24. Log.d(TAG, "uploadFile: " + response.toString());
  25. } catch (IOException e) {
  26. Log.e(TAG, "uploadFile: IOException" + e.getMessage(), e);
  27. }
  28. mDownloadStatus = DownloadStatus.FAILED_OR_EMPTY;
  29. return null;
  30. }

服务器端代码:

  1. public String uploadFile() throws IOException, ServletException, FileUploadException {
  2. System.out.println("upload file on postAction: called");
  3. HttpServletRequest request = ServletActionContext.getRequest();
  4. List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
  5. System.out.println("items size: " + items.size());
  6. for(FileItem item: items) {
  7. if(item.isFormField()) {
  8. // get file
  9. } else {
  10. }
  11. }
  12. return null;
  13. }

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

oewdyzsn

oewdyzsn1#

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

  1. public String uploadFile() throws IOException, ServletException, FileUploadException {
  2. System.out.println("upload file on postAction: called");
  3. HttpServletRequest request = ServletActionContext.getRequest();
  4. MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest());
  5. Enumeration<String> fileParameterNames = multipartRequest.getFileParameterNames();
  6. if(fileParameterNames.hasMoreElements()) {
  7. String inputValue = fileParameterNames.nextElement();
  8. System.out.println("inputValue: " + inputValue);
  9. String[] localFileNames = multipartRequest.getFileNames(inputValue);
  10. for (String fn : localFileNames) {
  11. System.out.println("local filename = " + fn);
  12. }
  13. File[] files = multipartRequest.getFiles(inputValue);
  14. for (File cf : files) {
  15. File destFile = new File(POST_FILE_DESTINATION + localFileNames[0]);
  16. FileUtils.copyFile(cf, destFile);
  17. FileUtils.deleteQuietly(cf);
  18. }
  19. }
  20. return null
  21. }

此处引用

展开查看全部

相关问题