httpClient文件上传为啥无法进入服务端方法?
死都进不去http://127.0.0.1:8888/upload/processUpload这个方法中,各路大神知道怎么进去吗?
client:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.Path;
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.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 org.springframework.beans.factory.annotation.Autowired;
import ******.UploadService;
public class UploadClient {
private static UploadClient uploadClient;
public static UploadClient getInstance(){
if (uploadClient == null) {
uploadClient = new UploadClient();
}
return uploadClient;
}
@Autowired
UploadService uploadService;
/**
* 上传文件
*
* @param serverUrl
* 服务器地址
* @param localFilePath
* 本地文件路径
* @param serverFieldName
* @param params
* @return
* @throws Exception
*/
public String uploadFileImpl(String serverUrl, String localFilePath,
String serverFieldName, Map<String, String> params)
throws Exception {
String respStr = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(serverUrl);
FileBody binFileBody = new FileBody(new File(localFilePath));
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder
.create();
// add the file params
multipartEntityBuilder.addPart(serverFieldName, binFileBody);
// 设置上传的其他参数
setUploadParams(multipartEntityBuilder, params);
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
respStr = getRespString(resEntity);
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
System.out.println("resp=" + respStr);
return respStr;
}
/**
* 设置上传文件时所附带的其他参数
*
* @param multipartEntityBuilder
* @param params
*/
private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,
Map<String, String> params) {
if (params != null && params.size() > 0) {
Set<String> keys = params.keySet();
for (String key : keys) {
multipartEntityBuilder
.addPart(key, new StringBody(params.get(key),
ContentType.TEXT_PLAIN));
}
}
}
/**
* 将返回结果转化为String
*
* @param entity
* @return
* @throws Exception
*/
private String getRespString(HttpEntity entity) throws Exception {
if (entity == null) {
return null;
}
InputStream is = entity.getContent();
StringBuffer strBuf = new StringBuffer();
byte[] buffer = new byte[4096];
int r = 0;
while ((r = is.read(buffer)) > 0) {
strBuf.append(new String(buffer, 0, r, "UTF-8"));
}
return strBuf.toString();
}
}
server:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface UploadService {
/**
* 文件上传
*
* @param input
* @return
*/
public void processUpload(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
serverImpl:
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import *******.UploadService;
import *****.UploadClient;
import ******.CarApiServiceImpl;
@Path("/upload")
@Service("uploadService")
public class uploadServerImpl implements UploadService {
public static final Logger log4j = LoggerFactory
.getLogger(uploadServerImpl.class);
@Autowired
private UploadClient uploadClient;
@POST
@Path("/processUpload")
@Produces({ ContentType.APPLICATION_JSON_UTF_8 })
@Consumes({ MediaType.APPLICATION_JSON })
@Transactional(readOnly = false)
@Override
public void processUpload(HttpServletRequest request, HttpServletResponse response){
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//检测是不是存在上传文件
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
String path = request.getRealPath("/file_upload_path");//得到上传文件的存放目录
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
//指定在内存中缓存数据大小,单位为byte,这里设为1Mb
factory.setSizeThreshold(1024*1024);
//设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
factory.setRepository(new File("D:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// 指定单个上传文件的最大尺寸,单位:字节,这里设为50Mb
upload.setFileSizeMax(50 * 1024 * 1024);
//指定一次上传多个文件的总尺寸,单位:字节,这里设为50Mb
upload.setSizeMax(50 * 1024 * 1024);
upload.setHeaderEncoding("UTF-8");
List<FileItem> items = null;
try {
// 解析request请求
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
if(items!=null){
//解析表单项目
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
//如果是普通表单属性
if (item.isFormField()) {
//相当于input的name属性 <input type="text" name="content">
String name = item.getFieldName();
//input的value属性
String value = item.getString();
System.out.println("属性:" + name + " 属性值:" + value);
}
//如果是上传文件
else {
//属性名
String fieldName = item.getFieldName();
//上传文件路径
String fileName = item.getName();
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);// 获得上传文件的文件名
try {
item.write(new File(dir, fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
response.addHeader("token", "hello");
}
}
test:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.HttpEntity;
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.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import *****.UploadService;
public class UploadTest {
@Value("${file.upload.path}")
private String file_upload_path;
@Autowired
UploadService uploadService;
@Autowired
static UploadClient uploadClient;
public static void main(String[] args) throws ClientProtocolException, IOException, ParseException {
try {
Map<String,String> uploadParams = new LinkedHashMap<String, String>();
uploadParams.put("userImageContentType", "image");
uploadParams.put("userImageFileName", "testaa.png");
uploadClient.getInstance().uploadFileImpl(
"http://127.0.0.1:8888/upload/processUpload", "F:\\testpics\\aa.jpg",
"file_upload_path", uploadParams);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:8888/upload/processUpload");
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 等 最代码怎么获取牛币啊?
- 完 谁来告诉我最代码上线的时间,答对者给5牛币,先来先得
- 等 牛友们,大家好,你们做程序员多久了?现在还好吗?
- 完 在微信打开的页面里进行app下载
- 等 最代码2014年欢乐聚声会
- 完 mysql如何查询表数据并且对3个字段降序的SQL?
- 完 最代码牛币机制改革
- 完 成功的在bae上使用了自定义运行环境 jetty+nginx的组合,大家对jetty+nginx优化有哪些心得?
- 完 进来分享一下各位牛牛是如何加入最代码大家庭的?
- 等 为什么java BufferedImage类处理大图直接抛出内存溢出的异常?
- 等 最代码是否开发手机app客户端?
- 完 java程序员学习哪些java的技术?java有哪些框架?都能做哪方面的开发?
- 等 php格式网页文件怎么运行?
- 等 Java volatile值获取的问题
- 等 前端vue,拦截了登录后台后,返回的token,requests拦截token,但是发送请求的时候,就出现跨越异常
- 等 大专本科计算机科班怎么找到Java工作?
- 等 eclipse怎么把三个java swing游戏项目合成一个项目?
- 完 伙伴们,大家都有什么好的解压方式么,分享一下~
- 完 三四线城市,6、7k,运维工作,索然无味,想去辞职上培训,各位牛牛有什么建议嘛
- 等 jsp页面输入中文变成问号
- 等 JPA在线上运行一段时间后报错Caused by: java.lang.IncompatibleClassChangeError: null
- 等 PHP 这个规则用preg_match_all怎么写
- 等 大佬们,有没有知道Alfresco如何配置LDAP登录呢?
- 等 php的install目录是框架带的吗?