Spring文件上传

7 篇文章 0 订阅

近日需要做图片上传,于是乎顺便整理一下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;
 }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值