Spring 图片上传

准备工作

  1. Tomcat虚拟地址映射

springmvc.xml

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

<!-- 文件上传,id必须设置为multipartResolver -->
<bean id="multipartResolver"
	class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!-- 设置文件上传大小 -->
	<property name="maxUploadSize" value="5000000" />
</bean>

HTML

<input name="img_input" type="file" accept="image/*"/>

JavaScript

    //上传头像
    $("body").on("change", "input[name='img_input']", upload);
    function upload(e) {
        var file = e.target.files[0]; //获取图片资源
        // 只选择图片文件
        if (!file.type.match('image.*')) {
            return false;
        }

        var reader = new FileReader();

        reader.readAsDataURL(file); // 读取文件

        // 渲染文件
        reader.onload = function (arg) {
            $($(e.target).siblings("img")[0]).attr("src", arg.target.result);
        }

        //上传到服务器
        var form_data = new FormData();
        var s = $(this)[0].files[0];

        // 把上传的数据放入form_data
        form_data.append("img", s);
      
        $.ajax({
            url: "<%=path%>/xxx/xxx/xxx",
            type: 'POST',
            cache: false,
            data: form_data,
            processData: false,
            contentType: false,
            async: false,
            success: function (data) {
                if (data.success) {
                    art.dialog({
                        title: "提示信息",
                        icon: "succeed",
                        width: "300",
                        content: "<span style='font-size:10pt;'>上传成功!</span>",
                        cancel: true,
                        cancelVal: "关闭"
                    });
                }
            }
        })
    }

Controller

    @Value("#{configProperties['imgUploadUrl']}")
    private String imgUpload;
    
    //上传头像
    @ResponseBody
    @RequestMapping("/userPortrain/uploadImg")
    public ResultStatus uploadImg(@RequestParam("img") MultipartFile pictureFile, HttpServletRequest request) throws IOException {
        // 图片上传
        // 设置图片名称,不能重复,可以使用uuid
        String picName = UUID.randomUUID().toString();
        // 获取文件名
        String oriName = pictureFile.getOriginalFilename();
        // 获取图片后缀
        String extName = oriName.substring(oriName.lastIndexOf("."));
        //图片名
        String fileName = picName + extName;
        // 开始上传
        pictureFile.transferTo(new File(imgUpload + fileName));

        //上传成功后更新数据库对象
        //此处省略
      
        return ResultStatus.success();
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值