如何使用SpringMVC接收文件流上传和表单参数
这篇文章主要介绍“如何使用SpringMVC接收文件流上传和表单参数”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“如何使用SpringMVC接收文件流上传和表单参数”文章能帮助大家解决问题。
接收文件流上传和表单参数在SpringMVC中,接收文件流非常简单,我们可以写个接口用来接收一些文件,同时还可以接收表单参数。
代码参考如下:
JAVA服务端代码/***接收文件流**@paramrequest请求*@returnOK*/@RequestMapping(value="/receive/file",method=POST)publicStringreceiveFile(HttpServletRequestrequest){//转换为MultipartHttpServletRequestif(requestinstanceofMultipartHttpServletRequest){MultipartHttpServletRequestmultipartRequest=(MultipartHttpServletRequest)request;//通过表单中的参数名来接收文件流(可用file.getInputStream()来接收输入流)MultipartFilefile=multipartRequest.getFile("file");System.out.println("上传的文件名称:"+file.getOriginalFilename());System.out.println("上传的文件大小:"+file.getSize());//接收其他表单参数Stringname=multipartRequest.getParameter("name");Stringcontent=multipartRequest.getParameter("content");System.out.println("name:"+name);System.out.println("content:"+content);return"OK";}else{return"不是MultipartHttpServletRequest";}}HTML页面代码
<formaction="http://127.0.0.1:8080/receive/file"method="post"enctype="multipart/form-data"><inputtype="file"name="file"id="file"><inputtype="text"name="content"value="内容"><inputtype="text"name="name"value="名称"><buttontype="submit">提交请求</button></form>SpringMVC接收文件上传,并对文件做处理
http client版本4.1.1
spring版本3.2.11
在这个例子里面我接收了文件,并转发给另一个机器,其实接收的时候文件的流已经拿到了,想保存到本地,或者对文件分析,自己可以斟酌。
springmvc配置<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><context:component-scanbase-package="com"/><!--ifyouuseannotationyoumustconfigurefollowingsetting--><mvc:annotation-driven/><beanclass="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/><beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/><!--处理JSON--><beanclass="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><propertyname="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value></list></property></bean><mvc:default-servlet-handler/><!--日志输出拦截器--><mvc:interceptors><beanclass="com.steward.interceptor.AccessInteceptor"><propertyname="accessLog"><value>true</value></property></bean></mvc:interceptors><!--解析器--><beanclass="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"><propertyname="mediaTypes"><map><entrykey="html"value="text/html"/><entrykey="json"value="application/json"/></map></property><propertyname="viewResolvers"><list><refbean="viewResolver"/></list></property><propertyname="defaultViews"><list><beanclass="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/></list></property></bean><!--异常处理--><beanid="exceptionHandler"class="com.steward.exception.ExceptionHandler"/><!--文件上传--><beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/><!--配置freeMarker的模板路径--><beanid="viewResolver"class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"><propertyname="viewClass"value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property><propertyname="suffix"value=".html"></property><propertyname="contentType"value="text/html;charset=UTF-8"/><propertyname="requestContextAttribute"value="rc"></property></bean><beanid="freemarkerConfig"class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"><propertyname="templateLoaderPath"value="/WEB-INF/templates/"></property><propertyname="freemarkerSettings"><props><propkey="template_update_delay">0</prop><propkey="default_encoding">UTF-8</prop><propkey="locale">zh_CN</prop><propkey="number_format">0.##########</prop><propkey="template_exception_handler">ignore</prop></props></property><propertyname="freemarkerVariables"><map><entrykey="getVersion"value-ref="getVersion"/></map></property></bean><beanid="getVersion"class="com.steward.freemarker.GetVersion"/></beans>controller代码如下
@RequestMapping(value="/uploadFile",method=RequestMethod.POST)@ResponseBodypublicStringuploadFile(HttpServletRequestrequest)throwsException{FileOutputStreamfos=null;InputStreamin=null;StringfileUrl=null;try{//将当前上下文初始化给CommonsMutipartResolver(多部分解析器)CommonsMultipartResolvermultipartResolver=newCommonsMultipartResolver(request.getSession().getServletContext());//检查form中是否有enctype="multipart/form-data"if(multipartResolver.isMultipart(request)){//将request变成多部分requestMultipartHttpServletRequestmultiRequest=(MultipartHttpServletRequest)request;//获取multiRequest中所有的文件名Iteratoriterator=multiRequest.getFileNames();while(iterator.hasNext()){MultipartFilemultipartFile=multiRequest.getFile(iterator.next().toString());in=multipartFile.getInputStream();Filefile=newFile(multipartFile.getOriginalFilename());fos=newFileOutputStream(file);byte[]buff=newbyte[1024];intlen=0;while((len=in.read(buff))>0){fos.write(buff,0,len);}StringuploadUrl=platformHttpsDomain+"/uploadFile";HttpPostpost=newHttpPost(uploadUrl);HttpClienthttpclient=newDefaultHttpClient();MultipartEntityreqEntity=newMultipartEntity();reqEntity.addPart("file",newFileBody(file));post.setEntity(reqEntity);HttpResponseresponse=httpclient.execute(post);intstatusCode=response.getStatusLine().getStatusCode();if(statusCode==HttpStatus.SC_OK){fileUrl=EntityUtils.toString(response.getEntity());}file.deleteOnExit();}}}catch(Exceptione){e.printStackTrace();}finally{if(fos!=null){try{fos.close();}catch(IOExceptione){}}if(in!=null){try{in.close();}catch(IOExceptione){}}}returnfileUrl;}
关于“如何使用SpringMVC接收文件流上传和表单参数”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。