form表单中文件上传

最近在开发过程中遇到了表单文件和内容同时传递到后台的需求,由于使用了shiro框架,在后台接收的时候会遇到了类型转换的错误。尝试了很多解决办法,还好最终解决了。这里记录一下。


首先是前台代码:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <jsp:include page="/static/header.jsp"/>
</head>
<body>
  <form id= "uploadForm" enctype="multipart/form-data">
    <p >指定文件名: <input type="text" name="filename" value= ""/></p >
    <p >上传文件: <input type="file" name="file"/></ p>
    <input type="button" value="上传" onclick="doUpload()" />
  </form>
<jsp:include page="/static/footer.jsp"/>
<script type="text/javascript">
    function getRequestUrl() {
        var strFullPath = window.document.location.href;
        var strPath = window.document.location.pathname;
        var pos = strFullPath.indexOf(strPath);
        var prePath = strFullPath.substring(0, pos);
        var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
        var path = prePath + postPath;
        return path;
    }
    function doUpload() {
        var formData = new FormData($( "#uploadForm" )[0]);
        formData.append("CODE","123456");  //自定义参数传递
        $.ajax({
            url: getRequestUrl() + "/testUpLoadForm",
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert(data);
            }
        });
    }
</script>
</body>
</html>

后台控制层代码如下:

    @RequestMapping("/testUpLoadForm") 
    public void testUpLoadForm(HttpServletRequest request){
    //因为使用的shiro框架,因此这里传递过来的类型需要转换一下
        ShiroHttpServletRequest shiroRequest = (ShiroHttpServletRequest) request;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        MultipartHttpServletRequest multipartRequest =
                commonsMultipartResolver.resolveMultipart((HttpServletRequest) shiroRequest.getRequest());
        Iterator<String> itr = multipartRequest.getFileNames();
        MultipartFile multipartFile = null;
        while (itr.hasNext()) {
            multipartFile = multipartRequest.getFile(itr.next());
            String fileRealName1 =  multipartFile.getName();
            String fileRealName =  multipartFile.getOriginalFilename();
            System.out.println(fileRealName1);
            System.out.println(fileRealName);
        }
        String sName = multipartRequest.getParameter("filename");
        System.out.println("结束!");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值