package com.yihu.editor.util;

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 org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by Administrator on 2017/6/13 0013.
 */
public class Upload {

    /**
     * 中转文件
     *
     * @param files
     *            上传的文件
     * @return 响应结果
     */
    public static String httpClientUploadFile(String url,List<MultipartFile> files) {
        final String remote_url = url;// 第三方服务器请求地址
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(remote_url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            int i=0;
            for(MultipartFile file:files){
                String fileName = file.getOriginalFilename();
                builder.addBinaryBody("file"+i, file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
                builder.addTextBody("filename"+i, fileName);// 类似浏览器表单提交，对应input的name和value
                i++;
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
