Ajax异步上传在SSM框架中的应用

最近在做毕业设计,由于毕设中要实现图片上传和视频上传的功能。突然发现原来的Form表单中的file已经满足不了我了,于是在一番折腾之后终于让我找到了一个简便的上传方式。下面来和大家分享一下我的过程。
第1步:首先你需要一个ajax的上传文件的脚本,这里写图片描述就是这个脚本,在github上找到的,非常好用,云盘链接下载。下载完成后将它加进你的项目中。
链接:https://pan.baidu.com/s/1i57vxB3 密码:5ype
第2步:配置spring-servlet.xml文件,具体配置内容如下:

<!-- 文件上传 -->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  <property name="maxUploadSize">   
        <value>104857600</value>  
        </property>  
        <property name="maxInMemorySize"> 
          <value>4096</value>  
        </property> 
    </bean>

第3步:在jsp页面中引用上传的脚本,调用ajaxFileUpload函数

<script src="js/ajaxfileupload.js" type="text/javascript"></script>
<script type="text/javascript">
function imageUpload(){
        $.ajaxFileUpload({
            url : 'uploadSong.do', //用于文件上传的服务器端请求地址
            fileElementId : 'file1', //文件上传空间的id属性  <input type="file" id="file" name="file" />
            type : 'post',
            dataType : 'text', //返回值类型 一般设置为json
            success : function(data, status) //服务器成功响应处理函数
            {
                alert("歌曲上传成功");

            },
            error : function(data, status, e)//服务器响应失败处理函数
            {
                alert("歌曲上传失败");

            }
        });
    }
</script>

第4步:在controller中处理请求发来的数据

/**
     * 歌曲上传
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "uploadSong", method = RequestMethod.POST)
    public @ResponseBody
    String uploadSong(HttpServletRequest request,
                  HttpServletResponse response, ModelMap model,HttpSession session) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile mFile = multipartRequest.getFile("song");
        String path="H:\\毕业设计\\KTVworkspace\\KtvSystem\\WebContent\\video\\";//替换成你所要保存的文件的位置
        String filename = mFile.getOriginalFilename();
        System.out.println("filename:"+filename);
        InputStream inputStream = mFile.getInputStream();
        byte[] b = new byte[1048576];
        int length = inputStream.read(b);
        String url =path + filename;
        System.out.println(url);
        FileOutputStream outputStream = new FileOutputStream(url);
        outputStream.write(b, 0, length);
        inputStream.close();
        outputStream.close();
        return filename;
    }

哈哈哈,大功告成!这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_33624558/article/details/78885459