springmvc环境下使用ajaxfileupload.js进行文件上传

controller:

/* #region */

    @RequestMapping(produces = "text/html;charset=UTF-8", value = "/unisi-plugins-core-files/component-async/upload")
    @ResponseBody
    public String upload(@RequestParam("uname") String uname, @RequestParam MultipartFile[] image_file,
            HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 可以在上传文件的同时接收其它参数
        com.unisi.framework.core.utilities.ConsoleHelper.printOut("收到用户的文件上传请求");
        // 如果用的是Tomcat服务器,则文件会上传到\%TOMCAT_HOME%\webapps\YourWebProject\upload\文件夹中
        // 这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
        String realPath = request.getSession().getServletContext().getRealPath("/upload");
        // 设置响应给前台内容的数据格式
        response.setContentType("text/plain; charset=UTF-8");
        // 设置响应给前台内容的PrintWriter对象
        PrintWriter out = response.getWriter();
        // 上传文件的原名(即上传前的文件名字)
        String originalFilename = null;
        // 如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
        // 如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解
        // 上传多个文件时,前台表单中的所有<input
        // type="file"/>的name都应该是image_file,否则参数里的image_file无法获取到所有上传的文件
        for (MultipartFile myfile : image_file) {
            if (myfile.isEmpty()) {
                out.print("1`请选择文件后上传");
                out.flush();
                return null;
            } else {
                originalFilename = myfile.getOriginalFilename();
                com.unisi.framework.core.utilities.ConsoleHelper.printOut("文件原名: " + originalFilename);
                com.unisi.framework.core.utilities.ConsoleHelper.printOut("文件名称: " + myfile.getName());
                com.unisi.framework.core.utilities.ConsoleHelper.printOut("文件长度: " + myfile.getSize());
                com.unisi.framework.core.utilities.ConsoleHelper.printOut("文件类型: " + myfile.getContentType());
                try {
                    // 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
                    // 此处也可以使用Spring提供的MultipartFile.transferTo(File
                    // dest)方法实现文件的上传
                    FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, originalFilename));
                } catch (IOException e) {
                    com.unisi.framework.core.utilities.ConsoleHelper
                            .printOut("文件[" + originalFilename + "]上传失败,堆栈轨迹如下");
                    e.printStackTrace();
                    out.print("1`文件上传失败,请重试!");
                    out.flush();
                    return null;
                }
            }
        }
        // 此时在Windows下输出的是[D:Developapache-tomcat-6.0.36webappsAjaxFileUpload\upload愤怒的小鸟.jpg]
        // System.out.println(realPath + "\" + originalFilename);
        // 此时在Windows下输出的是[/AjaxFileUpload/upload/愤怒的小鸟.jpg]
        // System.out.println(request.getContextPath() + "/upload/" +
        // originalFilename);
        // 不推荐返回[realPath + "\" + originalFilename]的值
        // 因为在Windows下<img src="file:///D:/aa.jpg">能被firefox显示,而<img
        // src="D:/aa.jpg">firefox是不认的
        out.print("0`" + request.getContextPath() + "/upload/" + originalFilename);
        out.flush();
        return null;
    }
    /* #endregion */

springmvc配置文件:

<!-- region upload config -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760" />
    </bean>
    <!-- endregion spring -->

前台:



<
script type="text/javascript"> function ajaxFileUpload(){     //执行上传文件操作的函数     $.ajaxFileUpload({         //处理文件上传操作的服务器端地址(可以传参数,已亲测可用)         url:'地址?uname=玄玉',         secureuri:false,                       //是否启用安全提交,默认为false         fileElementId:'image_file',           //文件选择框的id属性         dataType:'text',                       //服务器返回的格式,可以是json或xml等         success:function(data, status){        //服务器响应成功时的处理函数            alert(111);         },         error:function(data, status, e){ //服务器响应失败时的处理函数             alert(222);         }     }); } </script> <input type="file" name="image_file" id="image_file" /> <input value="Upload" type="button" id="upload-form" name="upload-form" onclick="ajaxFileUpload()"/>

当然,除以上配置代码外要引用ajaxfileupload.js。如果还有问题可以留言给我。

原文地址:https://www.cnblogs.com/fan-yuan/p/5048846.html