org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException:

用ajax提交form表单上传文件,出现以下错误

org.apache.commons.fileupload.FileUploadBase$InvalidContentTypeException: the request doesn't contain a multipart/form-data or multipart/mixed stream, content type header is application/x-www-form-urlencoded; charset=UTF-8
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:947)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:310)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:334)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
at com.qiye.EnterpriseServlet.update(EnterpriseServlet.java:252)
at com.qiye.EnterpriseServlet.doPost(EnterpriseServlet.java:91)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.filter.MyFilter.doFilter(MyFilter.java:90)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

 

通过 传统的 form 表单提交的方式上传文件:

<form id= "uploadForm" action= "http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype ="multipart/form-data">  <h1 >测试通过Rest接口上传文件 </h1>  <p >指定文件名: <input type ="text" name="filename" /></p>  <p >上传文件: <input type ="file" name="file" /></p>  <p >关键字1: <input type ="text" name="keyword" /></p>  <p >关键字2: <input type ="text" name="keyword" /></p>  <p >关键字3: <input type ="text" name="keyword" /></p>  <input type ="submit" value="上传"/> </form> 

不过 传统的 form 表单提交会导致页面刷新, 但是在有些情况下,我们不希望页面被刷新,这种时候我们都是使用Ajax的方式进行请求的:

$.ajax({
  url : "http://localhost:8080/STS/rest/user",
 type : "POST",  data : $( '#postForm').serialize(),  success : function(data) {   $( '#serverResponse').html(data);  },  error : function(data) {   $( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText);  } }); 

如上,通过 $( '#postForm' ).serialize() 可以对form表单进行序列化,从而将form表单中的所有参数传递到服务端。

但是上述方式,只能传递一般的参数, 上传文件的文件流是无法被序列化并传递的。

不过如今主流浏览器都开始支持一个叫做FormData的对象,有了这个FormData,我们就可以轻松地使用Ajax方式进行文件 上传 了。

 

 

正确的方法是:

使用FormData,进行Ajax请求并上传文件

这里使用JQuery,但是老版本的JQuery比如1.2是不支持的,最好使用2.0或更新版本:
<form id= "uploadForm">
      <p >指定文件名: <input type="text" name="filename" value= ""/></p > <p >上传文件: <input type="file" name="file"/></ p> <input type="button" value="上传" οnclick="doUpload()" /> </form>
function doUpload() {
 var formData = new FormData($( "#uploadForm" )[0]);  $.ajax({   url: 'http://localhost:8080/cfJAX_RS/rest/file/upload' ,   type: 'POST',   data: formData,   async: false,   cache: false,   contentType: false,   processData: false,   success: function (returndata) {   alert(returndata);   },   error: function (returndata) {   alert(returndata);   }  }); }


一定要记得把form表单头里面除了id以为的数据去掉,不然会报错,为什么我也不知道



来自:http://www.tuicool.com/articles/IJrAna3

转载于:https://www.cnblogs.com/lanliying/p/4588632.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apachecommons-fileupload.jar放在应用程序的WEB-INF\lib下,即可使用。下面举例介绍如何使用它的文件上传功能。 所使用的fileUpload版本为1.2,环境为Eclipse3.3+MyEclipse6.0。FileUpload 是基于 Commons IO的,所以在进入项目前先确定Commons IO的jar包(本文使用commons-io-1.3.2.jar)在WEB-INF\lib下。 此文作示例工程可在文章最后的附件中下载。 示例1 最简单的例子,通过ServletFileUpload静态类来解析Request,工厂类FileItemFactory会对mulipart类的表单中的所有字段进行处理,不只是file字段。getName()得到文件名,getString()得到表单数据内容,isFormField()可判断是否为普通的表单项。 demo1.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> //必须是multipart的表单数据。 <form name="myform" action="demo1.jsp" method="post" enctype="multipart/form-data"> Your name: <br> <input type="text" name="name" size="15"><br> File:<br> <input type="file" name="myfile"><br> <br> <input type="submit" name="submit" value="Commit"> </form> </body> </html> demo1.jsp <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@ page import="org.apache.commons.fileupload.*"%> <%@ page import="org.apache.commons.fileupload.servlet.*"%> <%@ page import="org.apache.commons.fileupload.disk.*"%> <%@ page import="java.util.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <% boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。 if (isMultipart == true) { FileItemFactory factory = new DiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。 ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); //检查当前项目是普通表单项目还是上传文件。 if (item.isFormField()) {//如果是普通表单项目,显示表单内容。 String fieldName = item.getFieldName(); if (fieldName.equals("name")) //对应demo1.html中type="text" name="name" out.print("the field name is" + item.getString());//显示表单内容。 out.print("<br>"); } else {//如果是上传文件,显示文件名。 out.print("the upload file name is" + item.getName()); out.print("<br>"); } } } else { out.print("the enctype must be multipart/form-data"); } %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> </body> </html> 结果: the field name isjeff the upload file name isD:\C语言考试样题\作业题.rar 示例2 上传两个文件到指定的目录。 demo2.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> <form name="myform" action="demo2.jsp" method="post" enctype="multipart/form-data"> File1:<br> <input type="file" name="myfile"><br> File2:<br> <input type="file" name="myfile"><br> <br> <input type="submit" name="submit" value="Commit"> </form> </body> </html> demo2.jsp <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@ page import="org.apache.commons.fileupload.*"%> <%@ page import="org.apache.commons.fileupload.servlet.*"%> <%@ page import="org.apache.commons.fileupload.disk.*"%> <%@ page import="java.util.*"%> <%@ page import="java.io.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <%String uploadPath="D:\\\\temp"; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart==true){ try{ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request);//得到所有的文件 Iterator<FileItem> itr = items.iterator(); while(itr.hasNext()){//依次处理每个文件 FileItem item=(FileItem)itr.next(); String fileName=item.getName();//获得文件名,包括路径 if(fileName!=null){ File fullFile=new File(item.getName()); File savedFile=new File(uploadPath,fullFile.getName()); item.write(savedFile); } } out.print("upload succeed"); } catch(Exception e){ e.printStackTrace(); } } else{ out.println("the enctype must be multipart/form-data"); } %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> </body> </html> 结果: upload succeed 此时,在"D:\temp"下可以看到你上传的两个文件。 示例3 上传一个文件到指定的目录,并限定文件大小。 demo3.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> <form name="myform" action="demo3.jsp" method="post" enctype="multipart/form-data"> File:<br> <input type="file" name="myfile"><br> <br> <input type="submit" name="submit" value="Commit"> </form> </body> </html> demo3.jsp <%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@ page import="org.apache.commons.fileupload.*"%> <%@ page import="org.apache.commons.fileupload.servlet.*"%> <%@ page import="org.apache.commons.fileupload.disk.*"%> <%@ page import="java.util.*"%> <%@ page import="java.io.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <% File uploadPath = new File("D:\\temp");//上传文件目录 if (!uploadPath.exists()) { uploadPath.mkdirs(); } // 临时文件目录 File tempPathFile = new File("d:\\temp\\buffer\\"); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb factory.setRepository(tempPathFile);//设置缓冲区目录 // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB List<FileItem> items = upload.parseRequest(request);//得到所有的文件 Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fileName = fi.getName(); if (fileName != null) { File fullFile = new File(fi.getName()); File savedFile = new File(uploadPath, fullFile .getName()); fi.write(savedFile); } } out.print("upload succeed"); } catch (Exception e) { e.printStackTrace(); } %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> </body> </html> 示例4 利用Servlet来实现文件上传。 Upload.java package com.zj.sample; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @SuppressWarnings("serial") public class Upload extends HttpServlet { private String uploadPath = "D:\\temp"; // 上传文件的目录 private String tempPath = "d:\\temp\\buffer\\"; // 临时文件目录 File tempPathFile; @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb factory.setRepository(tempPathFile);// 设置缓冲区目录 // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB List<FileItem> items = upload.parseRequest(request);// 得到所有的文件 Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); String fileName = fi.getName(); if (fileName != null) { File fullFile = new File(fi.getName()); File savedFile = new File(uploadPath, fullFile.getName()); fi.write(savedFile); } } System.out.print("upload succeed"); } catch (Exception e) { // 可以跳转出错页面 e.printStackTrace(); } } public void init() throws ServletException { File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { uploadFile.mkdirs(); } File tempPathFile = new File(tempPath); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } } } demo4.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>File upload</title> </head> <body> // action="fileupload"对应web.xml中<servlet-mapping>中<url-pattern>的设置. <form name="myform" action="fileupload" method="post" enctype="multipart/form-data"> File:<br> <input type="file" name="myfile"><br> <br> <input type="submit" name="submit" value="Commit"> </form> </body> </html> web.xml <servlet> <servlet-name>Upload</servlet-name> <servlet-class>com.zj.sample.Upload</servlet-class> </servlet> <servlet-mapping> <servlet-name>Upload</servlet-name> <url-pattern>/fileupload</url-pattern> </servlet-mapping>

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值