導航:首頁 > 版本升級 > springrest上傳文件

springrest上傳文件

發布時間:2022-01-21 01:51:13

⑴ spring mvc restful能上傳多大文件

SpringMVC本身對Restful支持非常好。它的@RequestMapping、@RequestParam、@PathVariable、@ResponseBody註解很好的支持了REST。18.2CreatingRESTfulservices1.@RequestMappingSpringusesthe@.類似於struts的action-mapping。可以指定POST或者GET。2.@PathVariableThe@.用於抽取URL中的信息作為參數。(注意,不包括請求字元串,那是@RequestParam做的事情。)@RequestMapping("/owners/{ownerId}",method=RequestMethod.GET)publicStringfindOwner(@PathVariableStringownerId,Modelmodel){//}如果變數名與pathVariable名不一致,那麼需要指定:@RequestMapping("/owners/{ownerId}",method=RequestMethod.GET)publicStringfindOwner(@PathVariable("ownerId")StringtheOwner,Modelmodel){//implementationomitted}@,long,.3.@RequestParam官方文檔居然沒有對這個註解進行說明,估計是遺漏了(真不應該啊)。這個註解跟@PathVariable功能差不多,只是參數值的來源不一樣而已。它的取值來源是請求參數(querystring或者post表單欄位)。對了,因為它的來源可以是POST欄位,所以它支持更豐富和復雜的類型信息。比如文件對象:@RequestMapping("/imageUpload")(@RequestParam("name")Stringname,@RequestParam("description")Stringdescription,@RequestParam("image")MultipartFileimage)throwsIOException{this.imageDatabase.storeImage(name,image.getInputStream(),(int)image.getSize(),description);return"redirect:imageList";}還可以設置defaultValue:@RequestMapping("/imageUpload")(@RequestParam(value="name",defaultValue="arganzheng")Stringname,@RequestParam("description")Stringdescription,@RequestParam("image")MultipartFileimage)throwsIOException{this.imageDatabase.storeImage(name,image.getInputStream(),(int)image.getSize(),description);return"redirect:imageList";}4.@RequestBody和@ResponseBody這兩個註解其實用到了Spring的一個非常靈活的設計——HttpMessageConverter18.3.2HTTPMessageConversion與@RequestParam不同,@RequestBody和@ResponseBody是針對整個HTTP請求或者返回消息的。前者只是針對HTTP請求消息中的一個name=value鍵值對(名稱很貼切)。HtppMessageConverter負責將HTTP請求消息(HTTPrequestmessage)轉化為對象,或者將對象轉化為HTTP響應體(HTTPresponsebody)。{//.booleansupports(Classclazz);//.ListgetSupportedMediaTypes();//,andreturnsit.Tread(Classclazz,HttpInputMessageinputMessage)throwsIOException,;//.voidwrite(Tt,)throwsIOException,;}SpringMVC對HttpMessageConverter有多種默認實現,基本上不需要自己再自定義--convertsformdatato/--convertto/fromajavax.xml.transform.-convertto/-convertto/fromjsONusingJackson'sObjectMapperetc然而對於RESTful應用,用的最多的當然是。但是不是默認的HttpMessageConverter:lementsHandlerAdapter,Ordered,BeanFactoryAware{(){//(false);//SeeSPR-=newStringHttpMessageConverter();stringHttpMessageConverter.setWriteAcceptCharset(false);this.messageConverters=newHttpMessageConverter[]{(),stringHttpMessageConverter,newSourceHttpMessageConverter(),()};}}如上:默認的HttpMessageConverter是ByteArrayHttpMessageConverter、stringHttpMessageConverter、SourceHttpMessageConverter和轉換器。所以需要配置一下:text/plain;charset=GBK配置好了之後,就可以享受@Requestbody和@ResponseBody對JONS轉換的便利之處了:@RequestMapping(value="api",method=RequestMethod.POST)@(@RequestBodyApiapi,@RequestParam(value="afterApiId",required=false)IntegerafterApiId){Integerid=apiMetadataService.addApi(api);returnid>0;}@RequestMapping(value="api/{apiId}",method=RequestMethod.GET)@ResponseBodypublicApigetApi(@PathVariable("apiId")intapiId){returnapiMetadataService.getApi(apiId,Version.primary);}一般情況下我們是不需要自定義HttpMessageConverter,不過對於Restful應用,有時候我們需要返回jsonp數據:packageme.arganzheng.study.springmvc.util;importjava.io.IOException;importjava.io.PrintStream;importorg.codehaus.jackson.map.ObjectMapper;importorg.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;importorg.springframework.http.HttpOutputMessage;importorg.springframework.http.converter.;importorg.springframework.http.converter.json.;importorg.springframework.web.context.request.RequestAttributes;importorg.springframework.web.context.request.RequestContextHolder;importorg.springframework.web.context.request.ServletRequestAttributes;{(){ObjectMapperobjectMapper=newObjectMapper();objectMapper.setSerializationConfig(objectMapper.getSerializationConfig().withSerializationInclusion(Inclusion.NON_NULL));setObjectMapper(objectMapper);}@(Objecto,)throwsIOException,{StringjsonpCallback=null;RequestAttributesreqAttrs=RequestContextHolder.currentRequestAttributes();if(){jsonpCallback=((ServletRequestAttributes)reqAttrs).getRequest().getParameter("jsonpCallback");}if(jsonpCallback!=null){newPrintStream(outputMessage.getBody()).print(jsonpCallback+"(");}super.writeInternal(o,outputMessage);if(jsonpCallback!=null){newPrintStream(outputMessage.getBody()).println(");");}}}

⑵ resttemplate怎麼上傳文件流

定義一個簡單的restful介面
@RestController
public class TestController
{
@RequestMapping(value = "testPost", method = RequestMethod.POST)
public ResponseBean testPost(@RequestBody RequestBean requestBean)
{
ResponseBean responseBean = new ResponseBean();
responseBean.setRetCode("0000");
responseBean.setRetMsg("succ");

return responseBean;
}
}

使用RestTemplate訪問該服務
//請求地址
String url = "";
//入參
RequestBean requestBean = new RequestBean();
requestBean.setTest1("1");
requestBean.setTest2("2");
requestBean.setTest3("3");

RestTemplate restTemplate = new RestTemplate();
ResponseBean responseBean = restTemplate.postForObject(url, requestBean, ResponseBean.class);

從這個例子可以看出,使用restTemplate訪問restful介面非常的簡單粗暴無腦。(url,
requestMap, ResponseBean.class)這三個參數分別代表 請求地址、請求參數、HTTP響應轉換被轉換成的對象類型。
RestTemplate方法的名稱遵循命名約定,第一部分指出正在調用什麼HTTP方法,第二部分指示返回的內容。本例中調用了restTemplate.postForObject方法,post指調用了HTTP的post方法,Object指將HTTP響應轉換為您選擇的對象類型。還有其他很多類似的方法,有興趣的同學可以參考官方api。
三.手動指定轉換器(HttpMessageConverter)
我們知道,調用reseful介面傳遞的數據內容是json格式的字元串,返回的響應也是json格式的字元串。然而restTemplate.postForObject方法的請求參數RequestBean和返回參數ResponseBean卻都是java類。是RestTemplate通過HttpMessageConverter自動幫我們做了轉換的操作。
默認情況下RestTemplate自動幫我們注冊了一組HttpMessageConverter用來處理一些不同的contentType的請求。
如StringHttpMessageConverter來處理text/plain;來處理application/json;來處理application/xml。
你可以在org.springframework.http.converter包下找到所有spring幫我們實現好的轉換器。
如果現有的轉換器不能滿足你的需求,你還可以實現org.springframework.http.converter.HttpMessageConverter介面自己寫一個。詳情參考官方api。
選好了HttpMessageConverter後怎麼把它注冊到我們的RestTemplate中呢。
RestTemplate restTemplate = new RestTemplate();
//獲取RestTemplate默認配置好的所有轉換器
List<HttpMessageConverter> messageConverters = restTemplate.getMessageConverters();
//默認的在第7個 先把它移除掉
messageConverters.remove(6);
//添加上GSON的轉換器
messageConverters.add(6, new GsonHttpMessageConverter());

這個簡單的例子展示了如何使用GsonHttpMessageConverter替換掉默認用來處理application/json的。
四.設置底層連接方式
要創建一個RestTemplate的實例,您可以像上述例子中簡單地調用默認的無參數構造函數。這將使用java.NET包中的標准Java類作為底層實現來創建HTTP請求。
但很多時候我們需要像傳統的HttpClient那樣設置HTTP請求的一些屬性。RestTemplate使用了一種很偷懶的方式實現了這個需求,那就是直接使用一個HttpClient作為底層實現......
//生成一個設置了連接超時時間、請求超時時間、異常最大重試次數的httpClient
RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000).setSocketTimeout(30000).build();
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(config).setRetryHandler(new (5, false));
HttpClient httpClient = builder.build();
//使用httpClient創建一個ClientHttpRequestFactory的實現
ClientHttpRequestFactory requestFactory = new (httpClient);
//ClientHttpRequestFactory作為參數構造一個使用作為底層的RestTemplate
RestTemplate restTemplate = new RestTemplate(requestFactory);

五.設置攔截器(ClientHttpRequestInterceptor)
有時候我們需要對請求做一些通用的攔截設置,這就可以使用攔截器進行處理。攔截器需要我們實現org.springframework.http.client.ClientHttpRequestInterceptor介面自己寫。
舉個簡單的例子,寫一個在header中根據請求內容和地址添加令牌的攔截器。
public class TokenInterceptor implements ClientHttpRequestInterceptor
{
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException
{
//請求地址
String checkTokenUrl = request.getURI().getPath();
//token有效時間
int ttTime = (int) (System.currentTimeMillis() / 1000 + 1800);
//請求方法名 POST、GET等
String methodName = request.getMethod().name();
//請求內容
String requestBody = new String(body);
//生成令牌 此處調用一個自己寫的方法,有興趣的朋友可以自行google如何使用ak/sk生成token,此方法跟本教程無關,就不貼出來了
String token = TokenHelper.generateToken(checkTokenUrl, ttTime, methodName, requestBody);
//將令牌放入請求header中
request.getHeaders().add("X-Auth-Token",token);

return execution.execute(request, body);
}
}

創建RestTemplate實例的時候可以這樣向其中添加攔截器
RestTemplate restTemplate = new RestTemplate();
//向restTemplate中添加自定義的攔截器
restTemplate.getInterceptors().add(new TokenInterceptor());

⑶ java調用rest上傳文件的介面怎麼寫

介面是如何的,,,,上傳文件一般是按POST接收數據的

~~~~

⑷ 用spring註解可以發布rest服務嗎

使用spring註解是可以實現rest服務的,具體實現參考以下步驟代碼

1、配置web.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<context-param>
<!--rest配置文件的路徑,貌似不配置也是載入這個地址,這個地方有點疑問,大家指點指點-->
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<!--配置一個Servlet,有這個Servlet統一調度頁面的請求-->
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<!--映射路徑,不要寫成了/*那樣會攔截所有的訪問,連JSP頁面都訪問不了-->
<servlet-name>rest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>

2、配置rest-servlet.xml(這是spring的配置文件)

<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5.xsdhttp://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-2.5.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-lazy-init="true">

<description>Spring公共配置</description>

<!--檢測註解-->
<context:component-scanbase-package="com.liqiu"/>
<beanclass="org.springframework.web.servlet.mvc.annotation."/>
<beanclass="org.springframework.web.servlet.mvc.annotation."/>
<!--注冊視圖解析器,說白了就是根據返回值指定到某個頁面-->
<beanid="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"/>
<propertyname="prefix"value="/"></property><!--頁面文件的路徑,在根目錄下-->
</bean>
</beans>

3、Controller代碼實現

packagecom.liqiu.controller;

importjava.io.IOException;

importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;

importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/simple")
publicclassSimpleController{
//映射路徑/simple/index當訪問這個路徑時,執行這個方法
@RequestMapping("/index")
publicStringindex(HttpServletRequestrequest,HttpServletResponseresponse){
//response,request會自動傳進來
request.setAttribute("message","Hello,!");
return"index.jsp";
}
//根據ID獲取不同的內容,通過@PathVariable獲得屬性
@RequestMapping(value="/{id}",method=RequestMethod.GET)
publicStringget(@PathVariableStringid,HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException{
request.setAttribute("message","Hello,!<br/>ID:"+id+"");
//response.getWriter().write("Youputidis:"+id);
return"index.jsp";
//returnnull;
}
}

JSP頁面

<%@pagelanguage="java"pageEncoding="UTF-8"%>
<html>
<head>
<title>Spring3RESTful</title>
</head>

<body>
${message}
</body>
</html>

4、測試

在瀏覽器中輸入:http://localhost:8080/SpringREST/simple/index/,就可以看到效果。

也可以在頁面輸入不同的參數,獲得不同的內容,輸入地址:http://localhost:8080/SpringREST/simple/88888,這次執行的就是get方法,通過註解獲取ID值。

⑸ 如何通過Java客戶端程序通過rest介面訪問並上傳文件(文檔)到web伺服器

圖片目錄不在項目路徑下,直接通過HTTP訪問不到,如果你硬是要這么訪問,你可以自己寫一個Servlet,通過流的方式輸出,注意要吧Content-Type設置正確

⑹ springmvc使用rest格式需要到什麼包

在使用springmvc提供rest介面實現文件上傳時,有時為了測試需要使用RestTemplate進行調用,那麼在使用RestTemplate調用文件上傳介面時有什麼特別的地方呢?實際上只需要注意一點就行了,就是創建文件資源時需要使用org.springframework.core.io.FileSystemResource類,而不能直接使用Java.io.File對象。

Controller中的rest介面代碼如下:

[java] view plain
@ResponseBody
@RequestMapping(value = "/upload.do", method = RequestMethod.POST)
public String upload(String fileName, MultipartFile jarFile) {
// 下面是測試代碼
System.out.println(fileName);
String originalFilename = jarFile.getOriginalFilename();
System.out.println(originalFilename);
try {
String string = new String(jarFile.getBytes(), "UTF-8");
System.out.println(string);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// TODO 處理文件內容...
return "OK";
}

使用RestTemplate測試上傳代碼如下:

[java] view plain
@Test
public void testUpload() throws Exception {
String url = "http://127.0.0.1:8080/test/upload.do";
String filePath = "C:\\Users\\MikanMu\\Desktop\\test.txt";

RestTemplate rest = new RestTemplate();
FileSystemResource resource = new FileSystemResource(new File(filePath));
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("jarFile", resource);
param.add("fileName", "test.txt");

String string = rest.postForObject(url, param, String.class);
System.out.println(string);
}

其中:

[java] view plain
String string = rest.postForObject(url, param, String.class);
可以換成:

[java] view plain
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String,Object>>(param);
ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
System.out.println(responseEntity.getBody());

⑺ restful api上傳文件

不太清楚你寫這個借口的目的是什麼,一般我們做上傳都是前端通過控制項上傳後得到路徑,然後調用一個方法將路徑保存就可以了。你這個借口的目的是什麼?

先調用介面獲得路徑是保存路徑不一樣的情況才這樣做的。如果上傳的路徑是一樣的就沒有那個必要再去調用一次了

⑻ resttemplate怎麼傳multipartfile

建議你在電腦的搜索欄里搜索"Templates"或者"Template",大多數軟體採用」Templates「的名稱來建立模板文件夾。 安裝的程序不同,所列的」Templates「文件夾數目有別。應該有許多」Templates「出現在你的搜索欄里。然後依次打開各個」Templates「,查找你。

⑼ restfull 怎麼實現一個上傳下載文件的介面,java後端代碼怎麼實現,怎麼上傳下載過程是怎麼進行的。

你好,你想復雜了,上傳和下載文件於普通的做法差不多,區別在於rest風格上傳文件要用post方法,下載用get方法,而且URL符合rest風格的要求即可

⑽ REST協議可以傳文件流嗎

OSI應用層協議標准:MHS——報文處理系統(Mail)FTAM——文件傳送、存取和管理(回FTP)VTP——虛終端協議(Telnet)DS——目錄服務答TP——事務處理JTM——作業傳送與操縱RDA——遠程資料庫訪問文件傳送協議FTP(FileTransferProtocol)是Internet文件傳送的基礎。通過該協議,用戶可以從一個Internet主機向另一個Internet主機拷貝文件。FTP曾經是Internet中的一種重要的交流形式。目前,我們常常用它來從遠程主機中拷貝所需的各類軟體。

閱讀全文

與springrest上傳文件相關的資料

熱點內容
文件系統中源程序是 瀏覽:538
word代碼背景 瀏覽:790
小電影網站有哪些 瀏覽:184
基於大數據的人才畫像 瀏覽:571
越南題材的中國電影 瀏覽:334
台灣紅羊公司出品的電影 瀏覽:261
網路大的未來發展趨勢 瀏覽:949
網路通信科目有哪些 瀏覽:942
有個女同藍頭發短發的電影叫什麼 瀏覽:697
appleshuffle紅色是4s耳機 瀏覽:60
日本生化女的電影 瀏覽:165
國產圖片視頻 瀏覽:479
oracle大數據瓶頸 瀏覽:576
法國啄木鳥電影名稱 瀏覽:630
蘋果11網路鎖怎麼解 瀏覽:276
城市大數據分析 瀏覽:291
法國電影一個男的兩個女的 瀏覽:212
妹妹和姐姐電影 瀏覽:999
linux串口後台運行 瀏覽:113
維語紅色電影 瀏覽:213

友情鏈接