Servlet文件上传||@MultipartConfig标注属性

在Servlet3.0之前,处理上传文件的操作一直是让开发者头疼的问题,因为Servlet本身没有对此提供直接的支持,需要使用第三方框架来实现,而且使用起来也不够简单。
Servlet3.0提供了对文件上传的支持,通过@MultipartConfig标注和HttpServletRequest的两个新方法getPart()和getParts(),开发者能够很容易实现文件的上传操作。

@MultipartConfig标注主要是为了辅助Servlet3.0中HttpServletRequest提供的对上传文件的支持。该标注写在Servlet类的声明之前,一表示该Servlet希望处理的请求时multipart/form-data类型的。另外,该标注还提供了若干属性用于简化对上传文件的处理。

@MultipartConfig标注属性

fileSizeThershold         int型      是(可选)     描述:当前数据量大于该值时,内容将被写入文件。

location               String型           是(可选)     描述:存放生成文件的地址

maxFileSize        long型             是(可选)     描述:允许上传的文件最大值,默认为-1,表示没有限制

maxRequestSize    long型         是(可选)     描述:针对 multipart/form-data 请求的最大数量,默认为-1,表示没有限制

<!--index.html文件部分代码-->
<form action="/HelloWorld/UpLoad" method="post" enctype="multipart/form-data">
	<input type="file" name="file">
	<input type="submit" name="upload" value="上传">
</form>

/*UpLoad.java为上传文件的Servlet类*/
package javaee.servlet;
import …………
//设置访问活着调用这个Servlet的路径
@WebServlet("/UpLoad")
//说明该Servlet处理的是multipart/form-data类型的请求
@MultipartConfig
public class UpLoad extends HttpServlet{
	private static final long serialVersionUID = 1L;
	public UpLoad(){
		super();
	}
	protected void doGet(HttpServletRequest request,HttpServletResponse response)
		throws ServletException,IOException{
		this.doPost(request, response);
	}
	protected void doPost(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		//说明输入的请求信息采用UTF-8编码方式
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		//Servlet3.0中新引入的方法,用来处理multipart/form-data类型编码的表单
		Part part = request.getPart("file");
		//获取HTTP头信息headerInfo=(form-data; name="file" filename="文件名")
		String headerInfo = part.getHeader("content-disposition");
		//从HTTP头信息中获取文件名fileName=(文件名)
		String fileName = headerInfo.substring(headerInfo.lastIndexOf("=") + 2, headerInfo.length() - 1);
		//获得存储上传文件的文件夹路径
		String fileSavingFolder = this.getServletContext().getRealPath("/UpLoad");
		//获得存储上传文件的完整路径(文件夹路径+文件名)
		//文件夹位置固定,文件夹采用与上传文件的原始名字相同
		String fileSavingPath = fileSavingFolder + File.separator + fileName;
		//如果存储上传文件的文件夹不存在,则创建文件夹
		File f = new File(fileSavingFolder + File.separator);
		if(!f.exists()){
			f.mkdirs();
		}
		//将上传的文件内容写入服务器文件中
		part.write(fileSavingPath);
		//输出上传成功信息
		out.println("文件上传成功~!");
	}
}

/DownLoadjava为下载文件的Servlet类*/
package javaee.servlet;
import …………
@WebServlet("/DownLoad")
public class DownLoad extends HttpServlet{
	private static final long serialVersionUID = 1L;
	public DownLoad(){
		super();
	}
	protected void doGet(HttpServletRequest request ,HttpServletResponse response)
			throws ServletException,IOException{
		this.doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,IOException{
		try{
			//服务器相对路径
			String filepath = "WEB-INF/web.xml";
			//服务器绝对路径
			String fullFilePath = getServletContext().getRealPath(filepath);
			System.out.println(fullFilePath);
			/*打开文件,创建File类型的文件对象*/
			File file = new File(fullFilePath);
			/*如果文件存在*/
			if(file.exists()){
				System.out.println("文件存在");
				/*获得文件名,并采用UTF-8编码方式进行编码,以解决中文问题*/
				String filename = URLEncoder.encode(file.getName(), "UTF-8");
				System.out.println(filename);
				/*重置response对象*/
				response.reset();
				//设置文件的类型,xml文件采用text/xml类型,详见MIME类型的说明
				response.setContentType("text/xml");
				//设置HTTP头信息中内容
				response.addHeader("Content-Disposition","attachment:filename=\"" + filename + "\"" );
				//设置文件的长度
				int fileLength = (int)file.length();
				System.out.println(fileLength);
				response.setContentLength(fileLength);
				/*如果文件长度大于0*/
				if(fileLength!=0){
					//创建输入流
					InputStream inStream = new FileInputStream(file);
					byte[] buf = new byte[4096];
					//创建输出流
					ServletOutputStream servletOS = response.getOutputStream();
					int readLength;
					//读取文件内容并写到response的输出流当中
					while(((readLength = inStream.read(buf))!=-1)){
						servletOS.write(buf, 0, readLength);
					}
					//关闭输入流
					inStream.close();
					//刷新输出缓冲
					servletOS.flush();
					//关闭输出流
					servletOS.close();
				}
			}else {
				System.out.println("文件不存在~!");
				PrintWriter out = response.getWriter();
				out.println("文件 \"" + fullFilePath + "\" 不存在");
			}
		}catch(Exception e){
			System.out.println(e);
		}
	}
}


出现问题: Unable to process parts as no multi-part configuration has been provided。。。。 Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided] with root cause java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided at org.apache.catalina.connector.Request.parseParts(Request.java:2734) at org.apache.catalina.connector.Request.getParts(Request.java:2701) at org.apache.catalina.connector.RequestFacade.getParts(RequestFacade.java:1083) at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:92) at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:85) at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:72) at org.springframework.web.multipart.support.MultipartResolutionDelegate.adaptToMultipartHttpServletRequest(MultipartResolutionDelegate.java:80) at org.springframework.web.multipart.support.MultipartResolutionDelegate.asMultipartHttpServletRequest(MultipartResolutionDelegate.java:74) at org.springframework.web.multipart.support.RequestPartServletServerHttpRequest.<init>(RequestPartServletServerHttpRequest.java:65) at org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolver.resolveArgument(RequestPartMethodArgumentResolver.java:126) at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121) at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:160) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) at javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) 配置以及相关代码 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>startspringmvc</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 设置根上下文配置文件位置 --> <context-param> <!-- 使用XML配置 --> <!-- <param-value>/WEB-INF/spring/root-context.xml</param-value> --> <!-- <param-name>contextConfigLocation</param-name> --> <!-- 使用XML配置 --> <param-name>contextClass</param-name> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>startspringmvcbyxml.RootConfig</param-value> </context-param> <!-- 注册ContextLoader-Listener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 注册Dispatcher-Servlet 同时配置了文件上传 --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextClass</param-name> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value>startspringmvcbyxml.WebConfig</param-value> </init-param> <load-on-startup>1</load-on-startup> <multipart-config> <location>/temp/spittle/uploads</location> <max-file-size>2097152</max-file-size> <max-request-size>4194304</max-request-size> </multipart-config> </servlet> <!-- 将Dispatcher映射到“/” --> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--配置文件上传 --> <!-- <servlet> <servlet-name>appServlet1</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> <multipart-config> <location>/temp/spittle/uploads</location> <max-file-size>2097152</max-file-size> <max-request-size>4194304</max-request-size> </multipart-config> </servlet> --> </web-app> package startspringmvcbyxml; import java.io.IOException; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.MultipartResolver; import org.springframework.web.multipart.support.StandardServletMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan public class WebConfig extends WebMvcConfigurerAdapter{ /** *配置视图解析器 */ @Bean public ViewResolver viewResovler(){ InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/views/"); resolver.setExposeContextBeansAsAttributes(true); resolver.setSuffix(".jsp"); resolver.setViewClass(JstlView.class);//InternalResourceViewResolver将视图解析为JstlView return resolver; } /** *配置静态资源处理 */ public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){ configurer.enable(); } /** *为文件上传配置的 */ @Bean public MultipartResolver mulitipartResovler() throws IOException{ return new StandardServletMultipartResolver(); } } @RequestMapping(value="/registerImg",method=RequestMethod.POST) public String processRegisteration(@RequestPart("profilePicture") byte[] profilePicture){ System.out.println("jin lai le"); return "uploading"; }
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付 9.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值