The front end receives multiple files and parameters and forwards records through the back end

Custom Catalog title is written here

Front end code passing

First of all, the definition of file format will not be mentioned here. As you basically know, what I want to say here is that I didn't know how to send it, especially in js.
Here we need to forward the request through ajax
Code:

`	 var str =$("#oprform")[0];
		 var formData = new FormData($("#oprform")[0]); `

Define var formdata = new FormData() to receive files
If parameters also need to be passed, add them in a loop

$('#param tr').each(
				function(i) {
					//Take fixed parameters
					if (0 < i && i <= 9) {
						var a = $(this).children('td').children("div").text();
						var b = $(this).children('td').children('input').val();
						param[a] = b;

                      formData.append(a,b);
					}
					//Take custom parameters
					if (i > 9) {
						var a = $(this).children('td').children('input').val();
						if (a != "") {
						//	param[a] = formData;
                            formData.append(a,$("#showfile"+i)[0].files[0]);
						}
					}
				})

In this way, all parameters can be carried to the back end.

back-end

How does the Java back end receive the values passed by the front end

 public ApiResponse handle(HttpServletRequest request, HttpServletResponse servletResponse) throws Exception

Received through the request of HttpServletRequest request,
There may be two situations: one is to ask for the file to be carried inside, the other is not to

No documents carried

Then the parameter httpReq.getParameter (String XX) can be obtained in the normal way;

Portable document

 // Transition to MultipartHttpRequest:
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
                Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
                // File upload
                if (fileMap.size() > 0) {
                    req.setMultipartFiles(fileMap);
                }

Here you need to convert the HttpServletRequest request to (MultipartHttpServletRequest) to get the files inside.
However, after the conversion, you may not be able to get parameters through httpReq.getParameter (String XX). You need to accept parameters in other ways. Therefore, it is recommended to get parameters first and convert them.

Forwarding request

RestTemplate

RestTemplate is a client provided by Spring to access the Rest service. RestTemplate provides a variety of convenient methods to access remote Http service, which can greatly improve the writing efficiency of the client. SpringBoot request mode is supported. Attention here

 MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(paramsMap.size());

This is the splicing method of parameter post passing, equivalent to & word connection

Use here

   FileSystemResource resource = new FileSystemResource(tempFilePath);

This is the input static file. The author steps in the hole that we must create a temporary file, and the temporary file can only be deleted after the post request mode. Otherwise, we can only pass the empty file.
I call delete again after passing. Remember to create temporary files and delete them after calling

public BizResponse requestForPost(String requestUrl, Map<String, MultipartFile> getMultipartFiles, String head, String bizcontent) {

        BizResponse bizResponse = new BizResponse() ;
        logger.info("Service call start:" + DateUtil.getCurrDate(DateUtil.HHMMSSSSS));


        try {
            if (StringUtils.isEmpty(requestUrl)) {
                bizResponse = new BizResponse(CodeConstant.CODE_EXCEPTION, "Interface address does not exist");

            } else {
                Map<String, String> headMap = JSON.parseObject(head, Map.class);
                Map<String, String> paramsMap = JSON.parseObject(bizcontent, Map.class);
                paramsMap = paramsMap == null ? new HashMap<>(6) : paramsMap;
                // Client IP
                paramsMap.put("clientIp", StringUtil.getString(IpUtil.getIp()));
                MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(paramsMap.size());
                paramsMap.forEach((key, value) -> {
                    map.add(key, value);
                });
                getMultipartFiles.forEach((key, value) -> {
                    MultipartFile file = value;
                    //Temporary storage address of documents
                    String tempFilePath = System.getProperty("java.io.tmpdir") + file.getOriginalFilename();
                    File tempFile = new File(tempFilePath);
                    try {
                        file.transferTo(tempFile);//Generate temporary files
                    } catch (IOException e) {
                        logger.info("File generation error:" + DateUtil.getCurrDate(DateUtil.HHMMSSSSS));
                        e.printStackTrace();
                    }
                    FileSystemResource resource = new FileSystemResource(tempFilePath);
                    map.add(key, resource);

                });
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("multipart/form-data");
                headers.setContentType(type);
                if (headMap != null || headMap.size() > 0) {
                    headers.setAll(headMap);
                }
                HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(map, headers);
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//
                ResponseEntity<String> responseEntity =
                        restTemplate.postForEntity(requestUrl, files, String.class);
//                bizResponse.setData(responseEntity.getBody());
//                bizResponse.setSubCode(responseEntity.getStatusCodeValue());

                bizResponse.setData(responseEntity.getBody());
                bizResponse.setSubCode(200);
                getMultipartFiles.forEach((key, value) -> {
                    MultipartFile file = value;
                    //Temporary storage address of documents
                    String tempFilePath = System.getProperty("java.io.tmpdir") + file.getOriginalFilename();
                    File tempFile = new File(tempFilePath);
                  tempFile.delete();

                });
            }
        } catch (Exception e) {
            // Request degradation processing
            logger.error("Service degradation request exception:" + e.getMessage());
        } finally {
            logger.info("End of service call:" + DateUtil.getCurrDate(DateUtil.HHMMSSSSS));
        }
        return bizResponse;
    }

HttpClient

Here, we also use HttpServletRequest to get the previous parameters

public String submitApiTest(HttpServletRequest request, HttpServletResponse response)

Then turn the request to

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
public static String doPost(String url, Map<String, String> param, Map<String, String> headerMap,
			MultipartFile file) {
		JSONObject json = new JSONObject();
		CloseableHttpClient httpclient = getHttpClient();
		CloseableHttpResponse response = null;
		String result = "";
		// Using RFC6532 to solve the problem of Chinese scrambling
		MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);

		try {
			// https filter certificate verification
			if (url.startsWith(HTTPS)) {
				HttpClient httpsclient = HttpClientFactory.getHttpsClient();
				HttpResponse responsehttps = null;
				// Create httpPost request
				HttpPost httpPost = new HttpPost(url.trim());

				// Create a header parameter list
				if (headerMap != null) {
					for (String key : headerMap.keySet()) {
						httpPost.addHeader(key, headerMap.get(key));
					}
				}

				// Create parameter list
				if (param != null) {
					
						if (file != null) {
							mEntityBuilder.addBinaryBody("file", file.getInputStream(), ContentType.DEFAULT_BINARY,
									file.getOriginalFilename());
							httpPost.setEntity(mEntityBuilder.build());
						} else {
							List<NameValuePair> paramList = new ArrayList<NameValuePair>();
							for (String key : param.keySet()) {
								paramList.add(new BasicNameValuePair(key, StringUtil.getString(param.get(key))));
							}
							UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
							httpPost.setEntity(entity);
						}
					} 
						UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
						httpPost.setEntity(entity);
					}

				}

				httpPost.setConfig(CONFIG);
				// Execution request
				responsehttps = httpsclient.execute(httpPost);
				int statusCode = responsehttps.getStatusLine().getStatusCode();
				// state = 200
				if (statusCode == STATE) {
					result = EntityUtils.toString(responsehttps.getEntity(), "utf-8");
				} else {
					json.put("error_code", "10000");
					json.put("reason", "http Status code:" + statusCode);
					result = json.toString();
				}
		

		} catch (Exception e) {
			json.put("error_code", "10000");
			json.put("reason", e.getMessage());
			result = json.toString();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
			}
		}
		return result;
	}

Published 12 original articles, won praise 1, visited 155
Private letter follow

Tags: JSON Java Spring REST

Posted on Thu, 12 Mar 2020 22:36:49 -0400 by drdapoo