Spring MVC利用Ajax上传图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40369944/article/details/83618526

html

<input type="file" onchange="imageUpload(this)" class="form-control" placeholder="点击按钮选择图片"id="pictureUpload">

Ajax

function imageUpload(obj) {
        //判断图片格式
        var fileName=obj.value;
        var suffixIndex=fileName.lastIndexOf(".");
        var suffix=fileName.substring(suffixIndex+1).toUpperCase();
        if(suffix!="BMP"&&suffix!="JPG"&&suffix!="JPEG"&&suffix!="PNG"&&suffix!="GIF"){
            layer.msg( "请上传图片(格式BMP、JPG、JPEG、PNG、GIF等)!");
            var file = $("#pictureUpload");
            file.after(file.clone().val(""));
            file.remove();
            return;
        }

        var formData = new FormData();
        formData.append('file', $('#pictureUpload')[0].files[0]);  //添加图片信息的参数
        $.ajax({
            type: "POST",
            url: "/fileUploadPage.do",
            data:formData,
            cache: false, //上传文件不需要缓存
            processData: false,// 告诉jQuery不要去处理发送的数据
            contentType: false,// 告诉jQuery不要去设置Content-Type请求头
            encType:"multipart/form-data",
            success: function(data) {
                alert(data)
            }
        });

    }

Controller

    @RequestMapping(value = "/fileUploadPage.do", method = RequestMethod.POST)
    @ResponseBody
    public String upload(HttpServletRequest req) throws Exception{
        MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
        MultipartFile file = mreq.getFile("file");
        String fileName = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String name=req.getSession().getServletContext().getRealPath("/")+
                "upload\\"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.'));
        FileOutputStream fos = new FileOutputStream(name);
        fos.write(file.getBytes());
        fos.flush();
        fos.close();
        return name;
    }

在spring.xml中添加

    <!--配置MultipartResolver:用于处理表单中的file-->
    <!-- 文件上传配置,这里id的名称固定写法 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>		<!--请求的编码格式-->
        <property name="maxUploadSize" value="102400000"></property>	<!--文件最大大小(字节) 1024*1024*50=50M-->
        <property name="resolveLazily" value="true"/>			<!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="uploadTempDir" value="upload"></property>		<!--指定上传文件的临时文件夹,请在项目中创建好目录。-->
    </bean>

猜你喜欢

转载自blog.csdn.net/qq_40369944/article/details/83618526