This article outlines:
There may be some requirements for services deployed internally or in a separate environment to provide rest services. These interfaces are invoked by sending http requests from the back end. That requires constructing http requests at the back end. The scenarios to be solved in this paper are as follows:
Front-end multipartfile uploads files, back-end receives post requests, calls external interfaces, transfers file streams and other parameters
The contents include:
1. Front-end postman calls upload interface
2. Backend receives multipartfile files
3. Backend constructs post request with httpclient
4. Processing of Return Result after Calling External Interface
Code first:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/** *Front-end upload file, back-end receive post request, call external file upload interface */ @PostMapping(value = "uploadImage") public void uploadImage(Model model, @RequestParam(value = "image") MultipartFile image, String label) { log.info("=============uploadImage start================="); log.info("Image Processing Labels"+label); Map<String, Object> data = new HashMap<String, Object>(); log.info("start post Request Construction======"); String url ="http://ip:port/mytest/fileup "; // external interface to be invoked by the server Map<String, String> resultMap = new HashMap<String, String>(); //HTTP clients construct post requests CloseableHttpClient httpClient = HttpClients.createDefault(); try { log.info("post Requested url"+url); HttpPost httpPost = new HttpPost(url); //The parameter HttpMultipartMode.RFC6532 is set to avoid scrambling when the file name is in Chinese. MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532); String originFileName = null; originFileName = image.getOriginalFilename(); // File file1 = new File("/home/temp/download/1200-560.jpg"); //test external interface uploads local pictures directly builder.addBinaryBody("image", image.getBytes(), ContentType.MULTIPART_FORM_DATA, originFileName);// Set up the upload file stream (need to be the output stream) and the type of contentType builder.addTextBody("label",label);//Other parameters in post request // log.info("label of upload map"+label); HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost);// Executive submission HttpEntity responseEntity = response.getEntity();//Receive the content returned by calling the external interface if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){// String imageUrl = stringStringMap.get("data"); // data.put("path",imageUrl); // The contents returned are all in content InputStream content = responseEntity.getContent(); byte[] bytes = toByteArray(content); //base64 encoding the byte array. In this case, calling the external interface returns the image stream. String encodeStr = Base64.getEncoder().encodeToString(bytes); model.addAttribute("data",encodeStr); } } catch (Exception e) { model.addAttribute("code", "Error code"); model.addAttribute("message","Error message"); }finally {//Close the link to httpclient after processing try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } /** *Convert the input stream to the output stream without creating temporary files * @param input * @return * @throws IOException */ public byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); copy(input, output); return output.toByteArray(); }
The postman call interface is as follows
Potential pits:
1. Ensure that the back-end deployed network is connected to the external interface network invoked
2. When the backend receives the multipartfile file, it calls the external interface without processing, and it does not need to generate temporary files. The byte stream can be obtained directly by using the method provided by the multipartfile object.
3. To construct a post request, if it involves uploading files, set the correct contentType, as shown in the code above.
4. In the constructed post request, addBinaryBody() can pass either a file object or a stream. [If it is a stream, it needs to be an output stream]
5. The byte array is converted to a base64 string, as detailed in the code Notes section above
6. Converting the input stream to the output stream does not require writing temporary files, as shown in the code above.
The difference between a multipartfile object and a file:
Multipartfile is an interface, commonly referred to as multipartfile is set up in spring mvc. It is defined in spring MVC to pass file objects. The interface includes the following methods
byte[] bytes = multipartFile.getBytes();//Get byte arrays of multipartfile objects, convertible file streams, etc. String contentType = multipartFile.getContentType();//Get the header type of multipartfile InputStream inputStream = multipartFile.getInputStream();//Get the input stream String name = multipartFile.getName();//Get the filename String originalFilename = multipartFile.getOriginalFilename();//Get the initial file name long size = multipartFile.getSize();//Get file size boolean empty = multipartFile.isEmpty();//Judging whether the content of the object is empty multipartFile.transferTo(new File("File path"));//Specify a file path that writes the contents of the multipartfile object to the file. If you need to convert to a file object, you need to create a temporary file
MultipartFile is an interface that can be transformed by setting the properties of the Commons MultipartFile object.
Spring MVC is set as follows:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600"/>
<property name="maxInMemorySize" value="4096"/>
</bean>
Set the size of the uploaded file in spring boot:
spring.http.multipart.maxFileSize=50Mb // Maximum uploadable size of a single file
spring.http.multipart.maxRequestSize=1000Mb // Maximum size of the entire request (including header, etc.)