SpringMVC 文件上传以及整合七牛云

本文永久链接地址:http://ilvc.me/blog/post/53
转载请注明出处:iLvc 开源 博客系统 ---- SpringMVC 文件上传以及整合七牛云

摘要: 文件上传基本每个站点都需要,本篇就详细了解下文件上传。

  • springmvc 文件上传
  • 上传文件到 七牛云

不使用SpringMVC

使用SpringMVC

配置文件:

 <!-- 上传组件  配置一定不要写错,id名字不能改。 -->
     <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"/>  
        <property name="maxUploadSize" value="10000000"/>
    </bean>

前台html

<form action="xxx" method="post" ENCTYPE="multipart/form-data">
  <input type="file"  name="file"  />
  <input type="Submit" class="button" value="Submit" />
 </form>

注意1:文件上传<form > 要添加属性 ENCTYPE="multipart/form-data"
注意2:上传<input> 的 name 属性得值 要与后台一致,这个我们稍后再说。

后台处理

 @ResponseBody
     @RequestMapping("/upload")  
        public String upload( MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws IOException  
        {  
         UpImgResult result = new UpImgResult();

          //如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解   
            //如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且还要指定@RequestParam注解   
            //并且上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件   

           /* for(MultipartFile myfile : myfiles){*/   
                if(file.isEmpty()){   
                    System.out.println("文件未上传");   
                }else{   
                    System.out.println("文件长度: " + file.getSize());   
                    System.out.println("文件类型: " + file.getContentType());   
                    System.out.println("文件名称: " + file.getName());   
                    System.out.println("文件原名: " + file.getOriginalFilename());   
                    System.out.println("========================================");   
                    //如果用的是Tomcat服务器,则文件会上传到  
    //{服务发布位置}\\WEB-INF\\upload\\文件夹中   
                    String realPath = request.getSession().getServletContext().getRealPath("/resources/upload/");  
                    //这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的   
                    FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, file.getOriginalFilename()));   
                }   
            /*}   */
                result.setUrl("http://ol5smga16.bkt.clouddn.com/17-6-7/72452903.jpg");
                String gsonString = new Gson().toJson(result);  
                try {
                    ResponseUtil.write(gsonString,response);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            return null;  
        }

关键部分都在注释里,这里就不在赘述了。

上传文件到 七牛云
基本的要求,你得有个七牛云账号,并创建一个空间。

当你获得了accessKey,secretKeybucket时,你就可以来上传文件到七牛云了。
七牛云上传文件的方式有很多详细看官方文档。

    @RequestMapping(value="/qiuniuupload",method=RequestMethod.POST)
    public void testQiuNiu(MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception{
         UpImgResult result = new UpImgResult();
        User user = (User) request.getSession().getAttribute("currentUser");

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.autoZone());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证,然后准备上传
        String accessKey = "xxxxx";
        String secretKey = "xxxxxxx";
        String bucket = "xxxx";
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = null;
        /*  byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);*/
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            Response qresponse;
            try {
                qresponse = uploadManager.put(file.getInputStream(),key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(qresponse.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                result.setUrl("http://ooprvk5m6.bkt.clouddn.com/"+putRet.key);
                String gsonString = new Gson().toJson(result);
                user.setAvtar("http://ooprvk5m6.bkt.clouddn.com/"+putRet.key);
                userService.update(user);
                request.getSession().setAttribute("currentUser",userService.findUser(user));
                ResponseUtil.write(gsonString,response);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



    }

七牛云提供了上传DEMO,可以很容易的整合到自己的项目中,学习成本低。


*荆轲刺秦王

本文永久链接地址:http://ilvc.me/blog/post/53
转载请注明出处:iLvc 开源 博客系统 ---- SpringMVC 文件上传以及整合七牛云

猜你喜欢

转载自ilvc.iteye.com/blog/2378667