当前位置: 移动技术网 > IT编程>开发语言>Java > 使用HttpClient发送文件流到服务器端

使用HttpClient发送文件流到服务器端

2019年01月04日  | 移动技术网IT编程  | 我要评论
适用场景:
网络绝对路径的url文件或图片,不存储到本地,转换成stream,直接使用httpclient传送到springboot的服务端,将文件存储下来,并返回一个文件地址。目前分层架构的系统越来越多这种需求,所以记录下来以备不时之需。

1、调用端
首先引入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>

调用代码:

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;

/**
 * 文件传送
 * 发送文件流到服务器端
 * 服务器端使用springboot的multipartfile接收
 *
 * 适用场景:
 * 绝对路径的url文件,不存储到本地,转换成stream,直接使用httpclient传送到springboot
 *
 */
public class testupload {

    public static void main(string[] args) {
        //文件url,此处取豆瓣上的一个图片
        string fileurl ="https://img1.doubanio.com/view/photo/l/public/p2537149328.webp";
        try {
            //提取到文件名
            string filename = fileurl.substring(fileurl.lastindexof("/")+1);
            //转换成文件流
            inputstream is = new url(fileurl).openstream();

            //接收文件的服务器地址
            string uploadurl = "http://localhost:8003/fileupload";

            //创建httpclient
            closeablehttpclient httpclient = httpclients.createdefault();
            httppost httppost = new httppost(uploadurl);
            multipartentitybuilder builder = multipartentitybuilder.create();
            /*绑定文件参数,传入文件流和contenttype,此处也可以继续添加其他formdata参数*/
            builder.addbinarybody("file",is, contenttype.multipart_form_data,filename);
            httpentity entity = builder.build();
            httppost.setentity(entity);

            //执行提交
            httpresponse response = httpclient.execute(httppost);
            httpentity responseentity = response.getentity();
            if(responseentity != null){
                //将响应的内容转换成字符串
                string result = entityutils.tostring(responseentity, charset.forname("utf-8"));

                //此处根据服务器返回的参数转换,这里返回的是json格式
                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、服务端

服务端直接使用multipartfile接收即可

/**
     * 上传文件
     * 
     * @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);
    }

具体如何存储如何返回,因人而异,我这里返回的是json字符串。

其他:本文参考了博友vincent-li的博文,表示感谢:

 

 



如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网