项目是挂在微信端的,所以手机图片上传的功能的比较难的就是怎样打开手机的相册,然后读取照片。最后在Controller中读取文件,然后copy到指定的路径下。
小白在网上找了一些资料然后结合了大神给的例子,简单的实现了手机端上传图片的功能。
以下就是具体的代码:
2.在Controller中的代码
3.在spring-mvc的配置文件中配置信息:
总结:这种手机上传图片的实现方法比较简单,配置信息和前台的图片获取的时候的代码信息较少,适合新手操作。另外,正是因为比较简单,所以这中方法上传图片功能比较简单,而且在部分手机上操作的时候总是提示手机只能上传内存卡上的照片信息(安卓),如果手机没有内存卡,会提示无法上传照片。具体原因还在努力寻找……
小白在网上找了一些资料然后结合了大神给的例子,简单的实现了手机端上传图片的功能。
以下就是具体的代码:
1.在jsp页面中的代码:
<span style="font-size:24px;"><form method="post" action="<%=rootPath%>/complaint" onSubmit="return emptyCheck()" enctype="multipart/form-data">
<div id="container4-2" class="font20" style="background-color:#9fa0a0;margin-top:px;padding-top:0px;
text-align:center;border:0px;
border-bottom-left-radius:3px;border-bottom-right-radius: 3px;
color:#ffffff;">
<div style="margin-top:2px;"></div>
<!-- <input type="file" value="上传图片" style="border-width: "/> -->
<input type="file" name="file" style="position: absolute;opacity: 0.00"/>
</div>
</form></span>
2.在Controller中的代码
<span style="font-size:24px;"> </span><pre name="code" class="java"><span style="font-size:24px;"> //【解析器解析request的上下文】
CommonsMultipartResolver multipartResolver =
new CommonsMultipartResolver(request.getSession().getServletContext());
//先判断request中是否包涵multipart类型的数据,
if(multipartResolver.isMultipart(request)){
//再将request中的数据转化成multipart类型的数据
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator iter = multiRequest.getFileNames();
while(iter.hasNext()){
MultipartFile file = multiRequest.getFile((String)iter.next());
if(file != null){
fileName = file.getOriginalFilename();
String typeString=fileName.substring(fileName.lastIndexOf("."));
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String id = sdf.format(new Date());
nameString=id+typeString;
path = "C:\\newtomcat\\webapps\\mobile\\userImg";
localFile = new File(path , nameString);
clientComplaint.setPath(localFile.getPath());//
//写文件到本地
try {
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(path,nameString));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} </span>
3.在spring-mvc的配置文件中配置信息:
<span style="font-size:24px;"> <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="209715200" />
<property name="defaultEncoding" value="UTF-8" />
<property name="resolveLazily" value="true" />
<!-- 延迟加载 -->
</bean></span>
总结:这种手机上传图片的实现方法比较简单,配置信息和前台的图片获取的时候的代码信息较少,适合新手操作。另外,正是因为比较简单,所以这中方法上传图片功能比较简单,而且在部分手机上操作的时候总是提示手机只能上传内存卡上的照片信息(安卓),如果手机没有内存卡,会提示无法上传照片。具体原因还在努力寻找……