近日需要做图片上传,于是乎顺便整理一下spring文件上传
在页面需要做的
form标签添加如下属性
enctype="multipart/form-data"
以及文件上传input
<input type="file" name="uppicture1"/>
spring配置文件配置bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>
controller接收数据,
其中address=http://localhost:8080/cau_eduLED/static/image
path=D:\newAPPs\.metadata\.plugins\org.eclipse.wst.server.core\tmp6\wtpwebapps\cau_eduLED\static\image
address是数据库保存的链接,path是文件硬盘保存位置
@RequestMapping(value="addPicture",method=RequestMethod.POST)
public String addPicture(Model model,String upname,Long id, @RequestParam("uppicture1")CommonsMultipartFile[] picture1,HttpServletRequest request
) throws Exception{
String address =request.getScheme() //当前链接使用的协议
+"://" + request.getServerName()//服务器地址
+ ":" + request.getServerPort() //端口号
+ request.getContextPath()+"/static/image";
System.out.println(address);
String path = request.getRealPath("/addPicture");
path = path.substring(0,path.lastIndexOf("\\"))+"\\static\\image";
File file =new File(path);
System.out.println(path);
if(!file.exists()){
System.out.println("创建目录");
file.mkdir();
}
for (int i = 0; i < picture1.length; i++) {
Picture picture = new Picture();
String s = picture1[i].getOriginalFilename();
File file1 = new File(path, s);
if(!file1.exists()){
// 获取输出流
OutputStream os = new FileOutputStream(new File(path, s));
// 获取 输入流
InputStream is = picture1[i].getInputStream();
int len = 0;
byte[] buffer = new byte[400];
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.close();
is.close();
}
picture.setName(upname);
picture.setStatus("1");
picture.setUrl(address+"/"+s);
pictureService.save(picture);
}
return "redirect:addTeacher?id="+id;
}