使用httpclient上传文件

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.nio.charset.Charset;

public class TestSendFile {

    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.out.println("File path not given");
            System.exit(1);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080/kafka-api/upload");

            FileBody bin = new FileBody(new File(args[0]),ContentType.create("text/plain", Consts.UTF_8));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
            StringBody pk = new StringBody("hupu_bbs", ContentType.create("text/plain", Consts.UTF_8));
            StringBody topic = new StringBody("hupu_bbs_index_full", ContentType.create("text/plain", Consts.UTF_8));
            HttpEntity reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)//设置浏览器兼容模式,解决文件名乱码问题
                    .addPart("bin", bin)
                    .addPart("comment", comment)
                    .addPart("pk", pk)
                    .addPart("topic", topic)
                    .setCharset(Charset.forName("utf-8"))
                    .build();

            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}

服务端接收请求:

 @RequestMapping("/upload")
    public Object upload(@RequestParam(value = PUBLIC_SECRET_KEY_FIELD) String pk, @RequestParam(value = TOPIC_FIELD) String topic, HttpServletRequest request) throws IOException {
//    public String upload(HttpServletRequest request) throws IOException {
        System.out.println("====================" + pk + "," + topic + "===================");
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        ConfigurableWebApplicationContext context = (ConfigurableWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());

        final MessageChannel channel = context.getBean(topic + "_Channel", MessageChannel.class);

        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            MultipartFile file = multiRequest.getFile(iter.next());

            if (file != null) {

                LineIterator lineIterator = IOUtils.lineIterator(file.getInputStream(),"utf-8");
                while (lineIterator.hasNext()){
                    String line = lineIterator.next();
                    System.out.println(line);
                    channel.send(MessageBuilder.withPayload(line).setHeader(KafkaHeaders.MESSAGE_KEY, pk + "|" + rand.nextInt(24)).setHeader(KafkaHeaders.TOPIC, topic).build());
                }
                lineIterator.close();
//                String fileName = file.getOriginalFilename();
//                String path1 = Thread.currentThread()
//                        .getContextClassLoader().getResource("").getPath()
//                        + "download" + File.separator;
//
//                //  下面的加的日期是为了防止上传的名字一样
//                String path = path1
//                        + new SimpleDateFormat("yyyyMMddHHmmss")
//                        .format(new Date()) + fileName;
//
//                File localFile = new File(path);
//                Files.createParentDirs(localFile);
//                file.transferTo(localFile);
            }

        }


        Map<String, Object> map = new HashMap<String, Object>();
        map.put("resultCode", "00");
        map.put("description", "操作成功");
        return map;

    }

StringBody部分参数可以在服务端通过@RequestParam方式获取。

必须配置如下Bean,否则不能解析文件上传请求:

 <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver"   >
        <property name="defaultEncoding" value="utf-8" />
        <!--1024*200即200k-->
        <property name="maxUploadSize" value="204800"/>
        <!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
        <property name="maxUploadSizePerFile" value="204800"/>
    </bean>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值