描述:在工作中我们常常会用到图片上传功能, 例如,商城中的商品,用户头像等场景下需要用到。下面小刘讲解单图片上传和多图片上传以及预览图片的功能实现;
前言:本功能实现基于SSM框架,至于SSM框架的搭建,本文不再赘述。4
请看另一篇博客讲解:SSM框架的基本搭建_小刘的博客-CSDN博客_ssm框架
1.上传文件所必须的jar包以及spring的相关配置
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
spring.xml中添加配置
<!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<!-- 最大内存大小 -->
<property name="maxInMemorySize" value="10240"/>
<!-- 最大文件大小,-1为不限制大小 -->
<property name="maxUploadSize" value="-1"/>
</bean>
2.单图片页面上传前端代码
上图为单图片上传前台代码显示,以及预览,表单控件隐藏触发,既可假改变上传样式。(可更改你喜欢的)下图为效果:
3.前端多图片上传预览代码
<tr>
<td height="40px">
<input type="file" id="productFileId" multiple="multiple" name="productFiles" onchange="javascript:setImagePreviews(this.id);" accept="image/*" />
</td>
<td rowspan="2" colspan="4" id="productImagesId"></td>
</tr>
特别注意:如果你想上传到后台,你的form表单需要加入:
method="post" enctype="multipart/form-data" 标签:而且单图片和多图片的html代码略有不同,请细看;
4.后台文件上传的接口方法api
/**
* 上传单个文件方法
* @param request
* @param file
* @return
* @throws IOException
*/
public static boolean uploadOneFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
if (!file.isEmpty()) { //如果文件不为空,写入上传路径
String path = request.getSession().getServletContext().getRealPath("/images/upload"); //上传文件路径
//文件原始名字
String filename = file.getOriginalFilename();
String suffixLast = filename.substring(filename.lastIndexOf(".")); //获取文件后缀
String newFileName = Utils.getUUID()+suffixLast; //文件新名字
File filepath = new File(path, newFileName);
判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件当中
file.transferTo(new File(path + File.separator + newFileName));
String imageUrl="/images/upload/"+newFileName;
request.getSession().setAttribute("imageUploadUrl",imageUrl);
return true;
}
return false;
}
/**
* 上传多个文件方法
* @param request
* @param files
* @return
*/
public static boolean uploadManyFiles(
HttpServletRequest request,
@RequestParam("files") MultipartFile[] files){
String path = request.getSession().getServletContext().getRealPath("/images/upload");
try {
System.out.println("上传数组图片的长度是"+files.length);
if (files.length!=0){
String s="";
for (int i = 0; i < files.length; i++) {
/**
* 必须进行判断,否则数组会越界
*/
if (files[i].isEmpty()){
return false;
}
//文件原始名字
String filename = files[i].getOriginalFilename();
//获取文件后缀
String suffixLast = filename.substring(filename.lastIndexOf("."));
//文件新名字
String newFileName = Utils.getUUID()+suffixLast;
File filepath = new File(path, newFileName);
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
files[i].transferTo(new File(path + File.separator + newFileName));
s+="/images/upload/"+newFileName+"-";
}
System.out.println("这是我的图片拼接成的数组字符"+s);
request.getSession().setAttribute("imageUploadUrl",s);
return true;
}
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
4.1.单个文件上传的接口
@RequestMapping(value = "/addCompany")
@ResponseBody
public String addCompany(
HttpServletRequest request,
@RequestParam("file") MultipartFile file) throws IOException {
boolean b = Utils.uploadOneFile(request, file);
if (b){
String url = (String) request.getSession().getAttribute("imageUploadUrl");
return "单图片上传成功"+url;
}
return "单图片上传失败";
}
4.2.多图片文件上传的接口
@RequestMapping(value = "/addManyCompany")
@ResponseBody
public String addManyCompany(
HttpServletRequest request,
@RequestParam("files") MultipartFile[] files) throws IOException {
boolean b = Utils.uploadManyFiles(request, files);
if (b){
String urls = (String) request.getSession().getAttribute("imageUploadUrl");
String[] strings = urls.split("-");
for (String s:strings){
System.out.println("上传的数组图片"+s);
}
return "多图片上传成功"+urls;
}
return "多图片上传失败";
}
特别接口:比如你想商品类和其他类都上传图片的场景
/**
* 上传多图片和添加企业信息
* @param request
* @param file
* @param companyFiles
* @param productFiles
* @return
* @throws IOException
*/
@RequestMapping(value = "/addCompanyOneAndMore")
@ResponseBody
public String addCompanyOneAndMore(
HttpServletRequest request,
@ModelAttribute CompanyVO companyVO,
@RequestParam("file") MultipartFile file,
@RequestParam("companyFiles") MultipartFile[] companyFiles,
@RequestParam("productFiles") MultipartFile[] productFiles) throws IOException {
。。。。。。。。。。。。。。。。。。
}
方法不再赘述,和单图片多图片类似。如有不解,请加java爱好群大家交流:852665736;大家一起交流,群里都是热心好客的小伙伴,大家一同进步。
无偿免费分享源码以及技术和面试文档,更多优秀精致的源码技术栈分享请关注公众号:gh_817962068649