springMVC使用ajaxFailUpload上传图片

1.maven pom.xml文件中导入jar包
<!--fileupload 支持springMVC文件上传功能-->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
</dependency>

2.在jsp页面<head>标签内引入script文件(注意顺序)

    <script type="text/javascript" src="resources/js/jquery-3.3.1.min.js"></script>

    <script type="text/javascript" src="resources/js/ajaxFileUpload.js"></script>

3.springMVC.xml配置文件中(必须进行配置)

    <!--使用springMVC上传图片 ajaxFileUpload-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10485760" />
    </bean>
4.<input>标签(id属性,<script>中 ajaxFileUpload的fileElementId会用到)

 <input type="file" id="headImg" name="headImg"/>
5.在<script>标签中,我将ajaxFileUpload写在一个函数里,在需要用到上传图片的位置,调用该函数
function headImgUpload(){  //图片上传函数
    var results = "";
    var account = $("#account").val(); //account、identity 这两个变量,根据我的需求会在后面用到,阅读者可以根据自己的需求删掉或者修改这两个变量
    var identity = $("input[name='identity']:checked").val();
    $.ajaxFileUpload({
        url:"register/headImgUpload?account="+account+"&identity="+identity,//根据url访问controller层中的方法
        secureuri:false,
        fileElementId:"headImg", //<input>标签中的id属性
        type:"POST",
        dataType:"text", //服务器返回的数据类型
        success:function (result) {
            result = result.replace(/<pre.*?>/g, '');  //ajaxFileUpload会对服务器响应回来的text内容加上<pre style="....">text</pre>前后缀
            result = result.replace(/<PRE.*?>/g, '');
            result = result.replace("<PRE>", '');
            result = result.replace("</PRE>", '');
            result = result.replace("<pre>", '');
            result = result.replace("</pre>", '');
            result = JSON.parse(result);//转换为json格式
            results = result.result;
            alert(result);
        },
        error:function (data,status,error) {
            alert("失败!!!"+error);
        }
    });
}

6.controller层

@Controller
@RequestMapping(value = "register")
public class RegisterController {
    //用户头像上传
    @RequestMapping(value = "/headImgUpload",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> headImgUpload(@RequestParam MultipartFile headImg, String account, String identity, HttpServletRequest request){
        //上传的结果
        String result = "fail";
        //头像上传到的位置
        String imgRealPath = "";

        try{
            //确保上传的图片不为空
            if(headImg != null && !headImg.isEmpty()){
                //判断注册用户的身份,商户还是会员
                if(identity.equals("member")){
                    //会员
                    imgRealPath = request.getSession().getServletContext().getRealPath("/resources/image/member");
                }else if(identity.equals("businessman")){
                    //商户
                    imgRealPath = request.getSession().getServletContext().getRealPath("/resources/image/businessman");
                }
                System.out.println(imgRealPath);//在控制台打印一下路径

                //上传完成后保存的文件名
                String fileName= account + ".jpg";
                //文件夹不存在的话,新建一个
                File fileFolder = new File(imgRealPath);
                if(!fileFolder.exists()){
                    fileFolder.mkdirs();
                }
                File file = new File(fileFolder,fileName);
                //transferTo(),springMVC的方法,用于图片上传时,将内存中的图片写入磁盘
                headImg.transferTo(file);//会报IO异常
                result = "success";
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("result",result);
        return resultMap;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值