httpClient4 客户端 上传文件

 

 

1.引入jar包

compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.1'

compile group: 'commons-io', name: 'commons-io', version: '2.5'

compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.1.3'

compile group: 'org.apache.httpcomponents', name: 'httpcore', version: '4.4.6'

 

// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient

compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.2'

 

2.  客户端代码:

 

 package com.cloud.test;

import java.io.File;

import java.io.IOException;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Map.Entry;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.HttpStatus;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.mime.MultipartEntity;

import org.apache.http.entity.mime.content.FileBody;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

public class HttpFilePost {

public static void main(String[] args) {

//from属性名称

String formName="names";

//上传文件

String fileName ="d:/123456.txt";

        HttpFilePost json = new HttpFilePost();        

        String url ="http://localhost:8080/cloud_server/nocheck/file/upfile.do";

        

        try {

        Map<String,String> map = new HashMap<String,String>();

        map.put(formName, fileName);

        map.put("name2", fileName);

        map.put("name3", fileName);

       

json.post(url, map);

} catch (IOException e) {

e.printStackTrace();

}

//{"resData":{"status":"1","message":"成功","data":{"name3":"ccba2662b6fb4942b612753b87d78faa_123456.txt","desc":"?????","names":"8abeae1ee4b84dd6b8726139f00028fb_123456.txt","name2":"146aa57526da4db0a3e51149a6935b2a_123456.txt"}},"token":null}

}

public void post(String url,Map<String,String> fileList) throws ClientProtocolException, IOException {

//HttpClient httpclient = new DefaultHttpClient();

CloseableHttpClient httpclient = HttpClients.createDefault();

HttpPost post = new HttpPost(url);

//StringBody stringBody = new StringBody("文件的描述");

MultipartEntity entity = new MultipartEntity();

if(null != fileList){

Iterator<Entry<String, String>> item = fileList.entrySet().iterator();

while(item.hasNext()){

Entry<String,String> it = item.next();

FileBody fileBody = new FileBody(new File(it.getValue()));

entity.addPart(it.getKey(), fileBody);

}

}

//entity.addPart("desc", stringBody);

post.setEntity(entity);

HttpResponse response = httpclient.execute(post);

if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

HttpEntity entitys = response.getEntity();

if (entity != null) {

System.out.println(entity.getContentLength());

System.out.println(EntityUtils.toString(entitys));

}

}

httpclient.getConnectionManager().shutdown();

}

}

 

 

输出结果:

{"resData":{"status":"1","message":"成功","data":{"name3":"f764bc995c5d476da2b35e451984c45c_123456.txt","names":"01f55516d10b41bc846571a08c51edcb_123456.txt","name2":"5b3ed125df2a44388632ae1ee2266d9f_123456.txt"}},"token":null}

 

 

 

3. web 端代码:

 

package com.cloud.api.controller;

 

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import java.util.UUID;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileItemFactory;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

 

import com.cloud.api.pojo.ResReslt;

import com.cloud.api.pojo.ResultInfo;

import com.cloud.api.util.ComStatus;

 

@Controller

public class ToolsController extends BaseController {

 

public static final String PATH = "d://test";

 

@ResponseBody

@RequestMapping(value = "nocheck/file/upfile", method = RequestMethod.POST, produces = {

"application/json;charset=UTF-8" })

public ResReslt upFile(String req, HttpServletResponse response, HttpServletRequest request) {

// PrintWriter out = null;

// response.setContentType("text/html;charset=UTF-8");

//

 

ResReslt resReslt = new ResReslt();

Map<String, Object> map = new HashMap<String, Object>();

FileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

File directory = null;

List<FileItem> items = new ArrayList<FileItem>();

 

InputStream is = null;

 

FileOutputStream fos = null;

 

ResultInfo<Map<String,Object>> resultInfo = new ResultInfo<Map<String,Object>>();

 

try {

items = upload.parseRequest(request);

// 得到所有的文件

Iterator<FileItem> it = items.iterator();

while (it.hasNext()) {

FileItem fItem = (FileItem) it.next();

String fName = "";

Object fValue = null;

if (fItem.isFormField()) { // 普通文本框的值

fName = fItem.getFieldName();

fValue = fItem.getString("UTF-8");

map.put(fName, fValue);

} else { // 获取上传文件的值

fName = fItem.getFieldName();

fValue = fItem.getInputStream();

String name = fItem.getName();

if (name != null && !("".equals(name))) {

name = name.substring(name.lastIndexOf(File.separator) + 1);

 

directory = new File(PATH);

if (!directory.exists()) {

directory.mkdirs();

}

 

String preFile =UUID.randomUUID().toString().replace("-", "");

String filePath = (PATH) + File.separator + preFile+"_"+name;

 

map.put(fName,  preFile+"_"+name);

is = fItem.getInputStream();

fos = new FileOutputStream(filePath);

byte[] buffer = new byte[1024];

int len = 0;

while ((len = is.read(buffer, 0, 1024)) != -1) {

fos.write(buffer, 0, len);

}

fos.flush();

 

}

}

}

} catch (Exception e) {

logItr.error("读取http请求属性值出错" + e.getMessage());

resultInfo.setStatus(ComStatus.RESULTINFO_STATUS_FAILE);

resultInfo.setMessage(ComStatus.RESULTINFO_MESSAGE_FAILE);

 

 

} finally {

try {

if (null != fos) {

fos.close();

}

 

if (null != is) {

is.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

 

 

resultInfo.setData(map);

resReslt.setResData(resultInfo);

 

return resReslt;

}

 

}

 

猜你喜欢

转载自gjp014.iteye.com/blog/2357709