文件上传:file通过Ajax传到controller

pom.xml

 <!-- 导入poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.8</version>
        </dependency>
 <!-- 上传 -->        
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

springMVC.xml:

 <!-- 文件上传配置 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 上传的最大限制 -->
        <property name="maxUploadSize" value="209715200" />
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="UTF-8" />
        <!-- 上传文件的解析 -->
        <property name="resolveLazily" value="true" />
    </bean>

jsp:

<input type="file" class="excel_file" accept=".xlsx,.xls;">
<div class="operation_btn">
	<input onclick="uploadFile();" class="comfirm_btns" type="button" value="开始导入"/>
</div>

jsp页面效果:
在这里插入图片描述

js(注意:要用FormData传递参数,contentType,processData这两个参数需要设置上):

// 1.导入功能
function uploadFile() {
    var formData = new FormData();
    var excelFile = $(".excel_file")[0].files[0];
    if (excelFile == null) {
        alert("请选择Excel文件");
        return;
    }
    formData.append("excelFile", excelFile);
    $.ajax({
        type: "POST",
        url: webPath.webRoot + "/uploadProductExcel/upload.json",
        data: formData,
        dataType: "json",
        contentType: false, //不设置内容类型
		processData: false, //不处理数据
        success: function () {
            alert("成功");
        },
        error: function () {
            alert("失败");
        }
    });
}

controller:

@Controller
@RequestMapping("/uploadProductExcel")
public class UploadExcelController {

    //1.导入(上传文件)
    @RequestMapping("/upload")
    public void uploadProductExcel(Model model, @RequestParam(value = "excelFile") MultipartFile excelFile) {
       
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值