项目后台是用Spring搭建的,上传图片一直不行,最后的最后终于解决了,记下了,以后还会用的着。
android端 上传方法:
/**
* 上传参数和文件
* @param url
* @param paramters
* @param filesMap
* @return
* @throws Exception
*/
public static String uploadFile2(String url, Map<String, String> paramters,
Map<String, File> filesMap) throws Exception {
System.out.println("uploadFile2---------------");
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
/* 建立HTTPPost对象 */
HttpPost httpRequest = new HttpPost(url);
String strResult = "doPostError";
// 文件传输
MultipartEntity mEntity = new MultipartEntity();
//添加上传参数
for (Map.Entry<String, String> entry : paramters.entrySet()) {
ContentBody strBody = new StringBody(entry.getValue());
mEntity.addPart(entry.getKey(), strBody);
}
//添加上传的文件
Iterator<String> iterator = filesMap.keySet().iterator();
while (iterator.hasNext()) {
String fileName = iterator.next();
ContentBody cBody = new FileBody(filesMap.get(fileName));
mEntity.addPart(fileName, cBody);
System.out.println("while-----iterator fileName:"+fileName+" file:"+filesMap.get(fileName));
}
System.out.println("file length----->" + mEntity.getContentLength());
httpRequest.setEntity(mEntity);
/* 发送请求并等待响应 */
HttpResponse httpResponse = httpClient.execute(httpRequest);
/* 若状态码为200 ok */
if (httpResponse.getStatusLine().getStatusCode() == 200) {
/* 读返回数据 */
strResult = EntityUtils.toString(httpResponse.getEntity());
} else {
strResult = "Error Response: "
+ httpResponse.getStatusLine().toString();
}
// 关闭连接
httpClient.getConnectionManager().shutdown();
return strResult;
}
没什么好说的不过多解释。
后台原来的接收文件方法:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("do post");
// 设置request编码,主要是为了处理普通输入框中的中文问题
request.setCharacterEncoding("utf-8");
System.out.println("ShareCon----->request:"
+ request.getAttributeNames().toString());
Enumeration enumeration = request.getAttributeNames();
while (enumeration.hasMoreElements()) {
Object object = enumeration.nextElement();
System.out.println("enum----->" + object.toString());
}
// 这里对request进行封装,RequestContext提供了对request多个访问方法
org.apache.commons.fileupload.RequestContext requestContext = new ServletRequestContext(
request);
// 判断表单是否是Multipart类型的。这里可以直接对request进行判断,不过已经以前的用法了
if (FileUpload.isMultipartContent(requestContext)) {
PrintWriter out = response.getWriter();
// String savePath = getSavePath(request);
String pathroot = this.getClass().getClassLoader().getResource("/")
.getPath();
String path = pathroot.substring(1, pathroot.length() - 8)
+ "resources/img";
path = java.net.URLDecoder.decode(path, "UTF-8");
String savePath = path;
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置文件的缓存路径
factory.setRepository(new File(savePath));
File dir = new File(savePath);
if (!dir.exists()) {
dir.mkdirs();
}
// System.out.print("已经生成临时文件");
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置上传文件大小的上限,-1表示无上限
upload.setSizeMax(100000 * 1024 * 1024);
List items = new ArrayList();
try {
// 上传文件,并解析出所有的表单字段,包括普通字段和文件字段
items = upload.parseRequest(request);
System.out.println("items------->" + items.size());
} catch (FileUploadException e1) {
System.out.println("文件上传发生错误" + e1.getMessage());
}
// 下面对每个字段进行处理,分普通字段和文件字段
Iterator it = items.iterator();
System.out.println("sc-------it----");
while (it.hasNext()) {
System.out.println("it=" + it);
DiskFileItem fileItem = (DiskFileItem) it.next();
// 如果是普通字段
if (fileItem.isFormField()) {
System.out.println(fileItem.getFieldName()
+ " "
+ fileItem.getName()
+ " "
+ new String(fileItem.getString().getBytes(
"iso8859-1"), "gbk"));
} else {
System.out.println(fileItem.getFieldName() + " "
+ fileItem.getName() + " "
+ fileItem.isInMemory() + " "
+ fileItem.getContentType() + " "
+ fileItem.getSize());
// 保存文件,其实就是把缓存里的数据写到目标路径下
if (fileItem.getName() != null && fileItem.getSize() != 0) {
File fullFile = new File(fileItem.getName());
String fileName = getFileName(request, fileItem
.getName());
File newFile = new File(savePath + fileName);
try {
fileItem.write(newFile);
} catch (Exception e) {
e.printStackTrace();
out.print("{\"error\":\"upload error!\"}");
}
out.print("{\"url\":\"/upload/" + fileName + "\"}");
} else {
System.out.println("文件没有选择 或 文件内容为空");
}
}
}
}
}
items = upload.parseRequest(request); 得到的item的长度一直为0 ,上网找了找,试了一些方法,都没解决。
最后改成了这样
@RequestMapping(value = "/upload_pic", method = RequestMethod.POST)
@ResponseBody
public void uploadFile(HttpServletRequest request,
HttpServletResponse response,int id) throws IOException {
System.out.println("uploadFile------>");
DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
request.setCharacterEncoding("UTF-8");
Map<String, MultipartFile> files = req.getFileMap();
String pathroot = this.getClass().getClassLoader().getResource("/")
.getPath();
String path = pathroot.substring(1, pathroot.length() - 8)
+ "resources/img/";
for (String key : files.keySet()) {
MultipartFile file = files.get(key);
System.out.println(file.getName());
System.out.println(file.getSize());
FileOutputStream fileOutput;
path = java.net.URLDecoder.decode(path, "UTF-8");
String fileName = path+key;
System.out.println("save_path:"+fileName);
try {
fileOutput = new FileOutputStream(fileName);
fileOutput.write(file.getBytes());
fileOutput.flush();
fileOutput.close();
String filename = "xxxxxxxxxxxxxxxxxxx";
int nums = shareService.addSharePic(id,filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
解决问题
// 转型为MultipartHttpRequest
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 根据前台的name名称得到上传的文件 "file" 是前端 的参数名, 值就是 文件对象 File
MultipartFile file = multipartRequest.getFile("file");
String fileName = file.getOriginalFilename();
相关推荐
android客户端连接javaweb服务器,java web服务器采用SSM(spring+springMVC+mybatis)框架。服务器端即可以处理android请求,又可以处理浏览器jsp页面请求。
开源软硬件系统wumei-iot,可用于二次开发和学习,快速搭建自己的物联网/智能家居系统,包括前台,后台,移动端,硬件端 wumei-iot是一套开源的软硬件系统,可用于二次开发和学习,快速搭建自己的智能家居系统。 ...
通过安卓打开相机相册,使用SSM框架搭建后台接口,前端使用retrofit2进行文件传输 注:低门槛实现系列就是不涉及过深的知识点,不做过多的异常捕获,不过滤版本不判空,面向小白。 正文 首先需要搭建SSM框架,默认...
使用Apollo搭建的服务端,后台采用java编写,使用Spring MVC 框架搭建的后台; 客户端使用Android,验证并接收后台传递的消息
他除了提供了Android SDK外,还附带了Spring Boot搭建的后台服务以及Vue.js编写的后台管理界面。资源链接使用说明文档XUpdate版本更新
linjiashop:邻家小铺,轻量,简洁的单商户商城系统,前(vue)后(SpringBoot)端分 离,支持多平台(h5,小程序,app)linjiashop 是一个基于Spring Boot和Vue.js的web商城系统, 包含了商城的后台管理系统,手机h5,小程序...
Chrome Frame 会把最新版的Chrome Webkit 内核和JavaScript 引擎注入到IE中, IE浏览器将获得Chrome的性能和功能 目录 摘要 I ABSTRACT II 专业名词清单 III 第一章 绪论 1 1.1 研究背景与意义 1 1.2国内外相关...
linjiashop:邻家小铺,轻量,简洁的单商户商城系统,前(vue)后(SpringBoot)端分 离,支持多平台(h5,小程序,app)linjiashop 是一个基于Spring Boot和Vue.js的web商城系统, 包含了商城的后台管理系统,手机h5,小程序...
提供Jsp页面后台插入数据、显示数据 进度 2016.04.18 Spring + Jpa + Hibernate框架搭建,Jsp、json的demo测试通过 2016.04.20 支持Android端获取Marker简要与详细信息 2016.04.25 支持Android端注册、登录功能 2016...
该系统 是一个基于Spring Boot和Vue.js的web商城系统,包含了商城的后台管理系统,手机h5,小程序版本,也包含了app版本(基于flutter) 和uniapp版本(基于uniapp通过一套代码实现H5,Android,IOS,小程序等多平台。...
jspBB 论坛(问答)系统后台功能设置:基础设置、注册设置、邮箱设置、上传设置、水印设置、约束设置、敏感词 用户:角色管理、用户组管理、用户管理 内容:问题管理、回答管理、评论管理 系统:短信日志、访问日志...