上传图片到服务器

from表单提交方式

1.加入jar包

 

实现图片上传需要加入的jar包,如下图:

https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload/1.2.2

https://mvnrepository.com/artifact/commons-io/commons-io/2.4

把两个jar包放到工程的lib文件夹中

 

2.配置上传解析器

在springmvc.xml中配置文件上传解析器

    <!-- 上传图片解析器    此处的id不能改变-->
     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"></property>
     </bean>

3.jsp页面修改

在商品修改页面,打开图片上传功能,如下图:

设置表单可以进行文件上传,如下图:

enctype="multipart/form-data"

加上这个属性就可以一下上传多个文件了

4.图片上传

在更新商品方法中添加图片上传逻辑

//上传公司营业执照
@RequestMapping("/uploadBusinessLicense")
@ResponseBody
public ResultUtil uploadBusinessLicense(MultipartFile businessLicense, HttpSession session){
    if(businessLicense!=null){
        String realPath = session.getServletContext().getRealPath("/uploads/license");  //上传到项目根目录下的路径
        File file = new File(realPath);
        if(!file.exists()){   //判断改目录是否存在不存在就创建
            file.mkdirs();
        }

        String oriName = businessLicense.getOriginalFilename();  //获取到上传的时候的图片名
        String endName = oriName.substring(oriName.lastIndexOf("."));  //获取到后缀名
        //判断是否为图片
        if(!endName.matches("^(?i)[(PNG)|(GIF)|(JPG)|(JPEG)]+$")){
            return ResultUtil.isError("请上传图片!");
        }
        //如果图片超过512k返回false   自己定义
        if(businessLicense.getSize()>512*1024){
            return ResultUtil.isError("文件不支持>512KB!");
        }

        //重命名文件名   也可以使用UUID
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = simpleDateFormat.format(new Date());

        //String picName = UUID.randomUUID().toString();  uuid生成的名字
        String newName = oriName.substring(0,oriName.lastIndexOf("."))+"_"+format+endName;

        try {
            businessLicense.transferTo(new File(realPath+File.separator+newName));  //上传图片

            return ResultUtil.isOk(newName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.isError("上传失败,详细信息为"+e.getMessage());//ResultUtil.是我自己定义的返回类
        }
    }
    return ResultUtil.isError("上传图片为空");

}

ajax方式提交

js代码

//上传营业执照
$("#businessLicenseBtn").click(function () {  //加一个单击事件按钮
    var formd = new FormData($("#userCompleteForm")[0]);    //$("#userCompleteForm")[0]:把form表单对象转换为js对象
    $.ajax({
        url:"${pageContext.request.contextPath}/witkeyUserComplete/uploadBusinessLicense",//跳转到后台路径
        type:"post",
        data:formd,
        dataType:"json",
        processData:false,    //用form表单的enctype对象   这两个属性加上就行了
        contentType:false,      //默认为true,上传数据转为对象,为false  不转为对象
        success:function (data) {
            alert(data)
            if(data){
                //上传成功
                alert("上传成功")
                $("#img1").prop("src","${pageContext.request.contextPath}/uploads/license/"+data.businessLicense);
            }else{
                alert("上传失败!")
            }
        },
        error:function(){
            alert("上传失败!")
        }
    })

 

html代码

<form id="userCompleteForm" method="post" enctype="multipart/form-data">

       

<div  class="row" style="margin-top: 10px">
    <div class="col-xs-2">
        <label class="control-label">营业执照:</label>
    </div>
    <div class="col-xs-4 updateP1">
        <div style="width: 150px;height: 150px; border:1px solid #989898; ">
            <img style="width: 150px;height: 150px;" id="img1" src="../../uploads/license/${userComplete.data.businessLicense}" name="businessLicense"/>
        </div>
    </div>
    <div class="col-md-4">
        <div class="container">
            <div class="col-md-12">
                <input type="file" name="businessLicense" multiple>
            </div>
            &nbsp;&nbsp;&nbsp;&nbsp;<input type="button" id="businessLicenseBtn" value="重新上传">
        </div>
    </div>
</div>

</form>

后台代码跟上面一样

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值