使用httpclient上傳檔案
阿新 • • 發佈:2019-02-11
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>