文件上传支持File类型和Text类型的解决方案

在Web开发中,经常会遇到文件上传和文本类型的表单的提交。但后台总是只能获取一种,不能同时获取文件流和文本数据,经过研究现提供俩种解决方法。
方法一:使用smartupload组件,开发smartupload组件的公司官网貌似不在了。需要注意的是从网上下载的smartupload jar包没有处理中文乱码问题,需要自己修改源代码,重新编译。我附件里会附上我重新编译的Jar包供大家下载。

HTML代码

<body>
   <form action="Upload" method="post" enctype="multipart/form-data">
         上传文件  <input type="file" name="file"/><br/>
          姓名       <input type="text" name="username"/><br/>
          <input type="submit" name="usersubmit">     
   </form>
</body><pre name="code" class="java">protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
	    response.setCharacterEncoding("UTF-8");
	    SmartUpload smart=new SmartUpload();
	    try {
        //PageContext是jsp的内置对象,在servlet不能直接使用,需要做一些处理
        JspFactory jspxFactory = null;
        PageContext pageContext = null;
        jspxFactory = JspFactory.getDefaultFactory();
        pageContext = jspxFactory.getPageContext(this,request,response,"",true,8192,true);
        smart.initialize(pageContext);
		smart.upload();
		File file = smart.getFiles().getFile(0);
		String fieldName = file.getFileName();
		System.out.println(fieldName);
		System.out.println(this.getServletContext().getRealPath("/"));
		smart.save(this.getServletContext().getRealPath("/"));
		String username = smart.getRequest().getParameter("username");//昵称
		System.out.println(username);
		} catch (Exception e) {
			e.printStackTrace();
		}       
	}
关键是要在表单里加上 enctype="multipart/form-data
方法二:由于ajax提交不支持文件类型的,所以需要用到jquery-form.js
HTML代码
 <body>
   <form action="" method="post" enctype="multipart/form-data" id="showDataList">
         上传文件  <input type="file" name="file"/><br/>
          姓名     <input type="text" name="username"/><br/>
          <input type="button"  οnclick= submit_form(this)/>     
   </form>
 </body>
js代码
function submit_form(obj){
        var uploadfile = document.getElementById("uploadfile").value;
        if(uploadfile==null||uploadfile==""){
            layer.alert('请选择文件!');
            return ;
        }
        layer.confirm('确认添加?',function(index){
            var requestUrl = "/testcase/testCaseAdd";
            $("#showDataList").ajaxSubmit({
                type: 'post',
                url: requestUrl,
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                clearForm:"true",
                success: function(data) {
                    if(data){
                        layer.msg('已添加!',{icon:1,time:1500});
                        //需要刷新页面
                    }
                }
            });
      }
值的注意的是需要在spring mvc的配置文件中配置如下代码
 
<pre name="code" class="html"><!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver,支持文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="7000000" />
    </bean>
依赖的jar包,在pom.xml文件中配置
<!-- 文件上传 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
spring mvc 后台的代码
@RequestMapping("/testCaseAdd")
    public @ResponseBody Boolean testCaseAdd(@RequestParam("file")MultipartFile file,HttpServletRequest request) throws IOException {
       if(!file.isEmpty()) {
           // 文件保存路径
           String filePath = request.getSession().getServletContext().getRealPath("/") + "upload\\" + file.getOriginalFilename();
           // 转存文件
           file.transferTo(new File(filePath));
		   //从前台获取值
          String path = request.getParameter("savepath");
       }

表单中的text类型的数据直接可以通过request获取

以上俩中方法都可以用,第一种适合直接表单提交,第二种适合需要用ajax来提交表单的。

附上smartupload 下载地址 点击打开链接






 


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值