最近项目遇到添加用户时,添加用户照片的需求。在添加的过程中,需要进行对图片格式,图片大小进行限制,并指定存储路径,将图片添加到数据库中,接口如下:
// 上传视频照片,添加/修改 相关信息
@RequestMapping("uploadImg.do")
public Result uploadLabourImage(@RequestParam(value = "upfile", required = false) MultipartFile files[],
HttpServletRequest request, HttpServletResponse response,TUser tuser) {
FileEntity fileEntry = new FileEntity();
FileUploadTool fileUploadTool = new FileUploadTool();
// 定义变量标记当前的图片
Integer imgId = 0;
ArrayList<TUserImg> imgList = new ArrayList<>();
String currentPic = "";
Gson gson = new Gson();
try {
String info = "";
for (int i = 0; i < files.length; i++) {
fileEntry = fileUploadTool.createFile(files[i], request);
}
TUserImg imageInfo = new TUserImg();
imageInfo.setId(imgId + 1);
imageInfo.setImg(fileEntry.getTitleAlter());
imgList.add(imageInfo);
String imgJson = gson.toJson(imgList);
tuser.setCreatetime(new Date());
String cityid=tuser.getCityid().toString();
List<TLocation> list =tLocationService.selectcity(cityid);
System.out.println(list.get(0).getCode()+"======list.get(0).getCode()========");
System.out.println(list.get(0).getName()+"======list.get(0).getName()========");
tuser.setCityname(list.get(0).getName());
List<TIndustry> list2 =tIndustryService .showlist(null);
for(TIndustry li:list2){
if(tuser.getIndustryid().equals(li.getId())){
tuser.setIndustryname(li.getIndustryname());
}
}
tuser.setPicture(imgJson);
System.out.println(tuser.getCityid()+"=======tuser========"+tuser.getIndustryid());
// 插入数据库
if(tuser.getId() !=null){
tUserService.updateUser(tuser);
}else{
tUserService.insertlist(tuser);
}
System.out.println("服务图片路径---" + myservice + fileEntry.getTitleAlter());
} catch (Exception e) {
e.printStackTrace();
return new Result(false, e.getMessage());
}
return new Result(true, "文件上传成功");
}
springmvc.xml中需要配置:
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property
name="prefix" value="/page"></property>
<property name="suffix" value=".html"></property>
</bean>`
<!-- 配置多媒体解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定文件上传的最大值10MB,10*1024*1024 -->
<property name="maxUploadSize" value="104857600"></property>
</bean>
当然。到现在还没有能够完全实现上传功能,还有一些辅助文件。
见(二):https://blog.csdn.net/baidu_38878945/article/details/86561865