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("结束!");
    }
在Web开发form表单文件上传功能允许用户选择本地文件并将其上到服务器。实现这一功能通常涉及以下HTML和后端技术的配合: 1. HTML表单设置: - 使用`<form>`标签,并设置`enctype`属性为`multipart/form-data`。这是因为`multipart/form-data`能够处理文件数据这种二进制格式。 - 在`<form>`加入`<input type="file">`标签,让用户可以选择文件。为了提高用户体验,可以设置`accept`属性来限制用户可以选择的文件类型。 - 提供一个提交按钮,用户点击后会触发表单的提交。 示例代码: ```html <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" accept=".jpg,.png,.gif" /> <input type="submit" value="上文件" /> </form> ``` 2. 后端处理: - 服务器端接收文件数据时,需要根据设置的`enctype`来解析POST请求。 - 根据具体的编程语言和框架,后端可能需要使用特定的库或组件来处理文件上传。 - 在接收到文件数据后,后端通常会进行文件保存操作,并可能会执行一些额外的处理,比如验证文件类型、大小,以及为上文件生成安全的文件名等。 例如,在Python的Flask框架,可以使用`request.files`来接收上文件: ```python from flask import request @app.route('/upload', methods=['POST']) def upload_file(): file = request.files['file'] if file: filename = secure_filename(file.filename) file.save(os.path.join('/path/to/the/uploads', filename)) return '文件上传成功' ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值