基于SSM使用jquery.from.js实现ajax文件上传

本文介绍了一个使用JSP和Spring MVC实现文件上传的例子。前端包含文件输入和提交按钮,利用jQuery进行AJAX提交;后端通过MultipartFile接收文件,并将其保存到指定路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前端JSP页面代码


<body>
    <form id="queryForm" name="queryForm" action="" method="post">
        <input id="filename" name="filename" type="file">
        <button onclick="sub()">提交</button>
    </form>
</body>
<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
<script type="text/javascript" src="js/jquery.from.js"></script>
<script type="text/javascript">
    function sub() {
        $("#queryForm").ajaxSubmit({
            type : "POST",
            url : "upload.action",
            dataType : "json",
            success : function(data) {
                alert(data);
            }
        });
    }
</script>

后端代码

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Object upload(@RequestParam(value = "filename", required = false) MultipartFile filename)
            throws IOException {

        if (!filename.isEmpty()) {

            String url = "F:\\upload";

            File file = new File(url);

            if (!file.isDirectory() && !file.exists()) {
                file.mkdir();
            }

            InputStream is = filename.getInputStream();

            String name = filename.getOriginalFilename();

            FileOutputStream fileOutputStream = new FileOutputStream(url + "/" + name);

            byte[] b = new byte[is.available()];

            is.read(b);

            fileOutputStream.write(b);

        } else {
            return "on";
        }

        return "ok";
    }

实现文件上传时需在servlet.xml中添加配置

<!-- 配置MultipartResolver,用于上传文件,使用spring的CommonsMultipartResolver -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxInMemorySize" value="4096"></property>
        <property name="maxUploadSize" value="5000000"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值