Restful介面接收資料案例
阿新 • • 發佈:2018-12-09
1.構建工程
2. 實現FileuploadRestful類,繼承Spring框架中的MultiActionController類,實現多檔案接收
package com.cloud.controller; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; @Controller @RequestMapping("/fileUploadController") public class FileuploadRestful extends MultiActionController{ static MultipartFile clientFiles ; //http://localhost:8080/DataService/upload.jsp @RequestMapping(method=RequestMethod.POST, value="/uploadFiles/{uniqueField}/{dateTime}") public void uploadFiles(@PathVariable String uniqueField,@PathVariable String dateTime,HttpServletRequest request, HttpServletResponse response, @RequestParam("clientFile") MultipartFile clientFile, HttpSession session) throws IllegalStateException, IOException { JSONObject result = new JSONObject(); if (!clientFile.isEmpty()) { clientFiles = clientFile; System.out.println("================="+clientFile.getSize()); System.out.println("clientFiles="+clientFiles); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultiValueMap<String, MultipartFile> multiValueMap = multipartRequest.getMultiFileMap(); List<MultipartFile> file = multiValueMap.get("clientFile"); System.out.println("file="+file); String filename = file.get(0).getOriginalFilename(); SaveFileFromInputStream(file.get(0).getInputStream(),"C://sleep/",filename); System.out.println("success"); result.put("status", "success"); result.put("info", "upload file success"); } else{ result.put("status", "failed"); result.put("info", "please upload file!"); } writeToClient(response,result); } private void SaveFileFromInputStream(InputStream inputStream, String path, String filename) throws IOException { FileOutputStream fs=new FileOutputStream( path + "/"+ filename); byte[] buffer =new byte[1024*1024]; int bytesum = 0; int byteread = 0; while ((byteread=inputStream.read(buffer))!=-1) { bytesum+=byteread; fs.write(buffer,0,byteread); fs.flush(); } fs.close(); inputStream.close(); } private void writeToClient(HttpServletResponse response,Object resp) { response.setContentType("text/html;charset=utf-8"); PrintWriter writer = null; try{ writer = response.getWriter(); writer.write(resp.toString()); writer.flush(); }catch(Exception e) { e.printStackTrace(); }finally { if(writer!=null) writer.close(); } } }
3. 編寫rest-servlet.xml檔案,如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> <!--The first view resolver --> <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"> <!-- 解析器的執行順序 --> <property name="order" value="1" /> <!-- 這裡是否忽略掉accept header,預設就是false --> <property name="ignoreAcceptHeader" value="true" /> <!-- 如果所有的mediaType都沒匹配上,就會使用defaultContentType --> <property name="defaultContentType" value="application/json" /> <!-- 是否啟用副檔名支援,預設就是true --> <property name="favorPathExtension" value="true" /> <!-- 是否啟用引數支援,預設就是true --> <property name="favorParameter" value="false" /> <property name="mediaTypes"> <map> <entry key="json" value="application/json" /> <entry key="xml" value="application/xml" /> <entry key="html" value="text/html" /> </map> </property> <property name="defaultViews"> <list> <bean class="com.cloud.controller.MappingViewUtil"> </bean> <bean class="org.springframework.web.servlet.view.xml.MarshallingView"> <property name="marshaller"> <bean class="org.springframework.oxm.xstream.XStreamMarshaller" /> </property> </bean> </list> </property> </bean> </beans>
4. 載入到web.xml檔案中,程式碼如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" > <display-name>Pro</display-name> <context-param> <param-name>webAppRootKey</param-name> <param-value>webapp.DADS.root</param-value> </context-param> <context-param> <param-name>version</param-name> <param-value>2.4</param-value> </context-param> <context-param> <param-name>releaseTime</param-name> <param-value>11月27日</param-value> </context-param><!-- <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:com/Log/log4j.properties</param-value> </context-param> --><context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/applicationContext.xml</param-value> </context-param> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <servlet> <servlet-name>rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>rest</servlet-name> <url-pattern>*.json</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <session-config> <session-timeout>720</session-timeout> </session-config> </web-app>
測試,瀏覽器輸入:http://localhost:8080/DataService/upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>upload</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form method="post" action="<%=path %>/fileUploadController/uploadFiles.json" enctype="multipart/form-data">
<input type="file" name="clientFile" /><br/>
<input type="submit" value="上傳檔案 "/>
</form>
</body>
</html>