httpclient 上传图片

背景:前端上传图片,后台接收到,转发给第三方系统或文件系统。

jar包

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.5</version>
</dependency>

简易代码:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("file")
public class FileController {

    @RequestMapping(value = "upload")
    @ResponseBody
    public void upload(HttpServletRequest request) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile coverFile = multipartRequest.getFile("file");
            
            String url = "";
            Map<String,String> textMap =  new HashMap<>();
            HttpUtil.httpClient(url, textMap, coverFile.getName(), coverFile.getInputStream());
            
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


public class HttpUtil {

    public static String httpClient(String url,Map<String,String> textMap,
            String fileName,InputStream inputStream) throws ClientProtocolException, IOException{
        HttpClient context = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        
         MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
        //MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        
        for (Entry<String,String> param : textMap.entrySet()) {
            builder.addTextBody(param.getKey(),param.getValue(),ContentType.TEXT_PLAIN);
        }
        
        builder.addBinaryBody("file",inputStream,ContentType.MULTIPART_FORM_DATA,fileName);
        
        post.setEntity(builder.build());
        HttpResponse response = context.execute(post);
        
        String re = new String(EntityUtils.toByteArray(response.getEntity()));
        
        return re;
    }
}

相关推荐