Using HttpClient to send file stream to server

Applicable scenarios:
The URL file or picture of the absolute path of the network is not stored locally, but converted into stream. It is directly transmitted to the service end of spring boot using HTTP client to store the file and return a file address. At present, there are more and more systems with layered architecture, so it is necessary to record them for emergency.

1. Calling end
First, introduce the package required by httpclient
<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.4</version>
    </dependency>

Call code:

package test.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * File transfer
 * Send file stream to server
 * The server uses SpringBoot's MultipartFile to receive
 *
 * Applicable scenarios:
 * The URL file of absolute path, which is not stored locally, is converted into stream and directly transmitted to SpringBoot using HTTP client
 *
 */
public class TestUpload {

    public static void main(String[] args) {
        //file URL,Here is a picture on the bean petal
        String fileUrl ="https://img1.doubanio.com/view/photo/l/public/p2537149328.webp";
        try {
            //Extract to filename
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
            //Convert to file stream
            InputStream is = new URL(fileUrl).openStream();

            //Server address to receive files
            String uploadURL = "http://localhost:8003/fileupload";

            //Establish HttpClient
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(uploadURL);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            /*Bind file parameters, pass in file stream and contenttype, and you can continue to add other formdata parameters here*/
            builder.addBinaryBody("file",is, ContentType.MULTIPART_FORM_DATA,fileName);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            //Execution submission
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity != null){
                //Convert the content of the response to a string
                String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));

                //Here, according to the parameter conversion returned by the server, what is returned here is JSON format
                JSONObject output = JSON.parseObject(result);
                JSONArray body = output.getJSONArray("body");
                String resUrl = body.get(0)+"";

                System.out.println(resUrl);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}

 

2. Server

The server can receive directly with MultipartFile

/**
     * Upload files
     * 
     * @throws BusinessException
     */
    @PostMapping("")
    public String upload(@RequestParam(defaultValue = "", required = false) String prefix,
            @RequestParam("file") MultipartFile... files) throws BusinessException {
        ResultView<List<String>> resultView = new ResultView<>();
        List<String> list = new ArrayList<>();
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                log.warn("have empty upload file,you need check is right?");
                continue;
            }
            String filepath = storageService.store(file, prefix);
            list.add(fileServerAddress + filepath.replaceAll("\\\\", "/"));
        }

        resultView.setBody(list);
        log.info(JSONObject.toJSONString(resultView));
        return JSONObject.toJSONString(resultView);
    }

How to store and return is different from person to person. I return JSON string here.

Others: This article refers to Boyou Vincent-Li Thank you

https://www.cnblogs.com/lyxy/p/5629151.html

 

 



Tags: Java Apache JSON SpringBoot

Posted on Wed, 04 Dec 2019 13:27:30 -0500 by pspfreak101