您好,登錄后才能下訂單哦!
這篇文章主要介紹“如何使用SpringMVC接收文件流上傳和表單參數(shù)”的相關(guān)知識(shí),小編通過(guò)實(shí)際案例向大家展示操作過(guò)程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“如何使用SpringMVC接收文件流上傳和表單參數(shù)”文章能幫助大家解決問(wèn)題。
在SpringMVC中,接收文件流非常簡(jiǎn)單,我們可以寫(xiě)個(gè)接口用來(lái)接收一些文件,同時(shí)還可以接收表單參數(shù)。
代碼參考如下:
/** * 接收文件流 * * @param request 請(qǐng)求 * @return OK */ @RequestMapping(value = "/receive/file", method = POST) public String receiveFile(HttpServletRequest request) { // 轉(zhuǎn)換為 MultipartHttpServletRequest if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 通過(guò)表單中的參數(shù)名來(lái)接收文件流(可用 file.getInputStream() 來(lái)接收輸入流) MultipartFile file = multipartRequest.getFile("file"); System.out.println("上傳的文件名稱(chēng):" + file.getOriginalFilename()); System.out.println("上傳的文件大小:" + file.getSize()); // 接收其他表單參數(shù) String name = multipartRequest.getParameter("name"); String content = multipartRequest.getParameter("content"); System.out.println("name:" + name); System.out.println("content:" + content); return "OK"; } else { return "不是 MultipartHttpServletRequest"; } }
<form action="http://127.0.0.1:8080/receive/file" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="file"> <input type="text" name="content" value="內(nèi)容"> <input type="text" name="name" value="名稱(chēng)"> <button type="submit">提交請(qǐng)求</button> </form>
http client版本4.1.1
spring版本3.2.11
在這個(gè)例子里面我接收了文件,并轉(zhuǎn)發(fā)給另一個(gè)機(jī)器,其實(shí)接收的時(shí)候文件的流已經(jīng)拿到了,想保存到本地,或者對(duì)文件分析,自己可以斟酌。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com"/> <!-- if you use annotation you must configure following setting --> <mvc:annotation-driven/> <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!-- 處理JSON --> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <mvc:default-servlet-handler/> <!-- 日志輸出攔截器 --> <mvc:interceptors> <bean class="com.steward.interceptor.AccessInteceptor"> <property name="accessLog"> <value>true</value> </property> </bean> </mvc:interceptors> <!-- 解析器 --> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <property name="mediaTypes"> <map> <entry key="html" value="text/html"/> <entry key="json" value="application/json"/> </map> </property> <property name="viewResolvers"> <list> <ref bean="viewResolver"/> </list> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/> </list> </property> </bean> <!-- 異常處理 --> <bean id="exceptionHandler" class="com.steward.exception.ExceptionHandler"/> <!-- 文件上傳 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> <!-- 配置freeMarker的模板路徑 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"></property> <property name="suffix" value=".html"></property> <property name="contentType" value="text/html;charset=UTF-8"/> <property name="requestContextAttribute" value="rc"></property> </bean> <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/templates/"></property> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">0</prop> <prop key="default_encoding">UTF-8</prop> <prop key="locale">zh_CN</prop> <prop key="number_format">0.##########</prop> <prop key="template_exception_handler">ignore</prop> </props> </property> <property name="freemarkerVariables"> <map> <entry key="getVersion" value-ref="getVersion"/> </map> </property> </bean> <bean id="getVersion" class="com.steward.freemarker.GetVersion"/> </beans>
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody public String uploadFile(HttpServletRequest request) throws Exception { FileOutputStream fos = null; InputStream in = null; String fileUrl = null; try { //將當(dāng)前上下文初始化給 CommonsMutipartResolver (多部分解析器) CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //檢查form中是否有enctype="multipart/form-data" if (multipartResolver.isMultipart(request)) { //將request變成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //獲取multiRequest 中所有的文件名 Iterator iterator = multiRequest.getFileNames(); while (iterator.hasNext()) { MultipartFile multipartFile = multiRequest.getFile(iterator.next().toString()); in = multipartFile.getInputStream(); File file = new File(multipartFile.getOriginalFilename()); fos = new FileOutputStream(file); byte[] buff = new byte[1024]; int len = 0; while ((len = in.read(buff)) > 0) { fos.write(buff, 0, len); } String uploadUrl = platformHttpsDomain + "/uploadFile"; HttpPost post = new HttpPost(uploadUrl); HttpClient httpclient = new DefaultHttpClient(); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", new FileBody(file)); post.setEntity(reqEntity); HttpResponse response = httpclient.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { fileUrl = EntityUtils.toString(response.getEntity()); } file.deleteOnExit(); } } } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } } return fileUrl; }
關(guān)于“如何使用SpringMVC接收文件流上傳和表單參數(shù)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。