导航:首页 > 版本升级 > 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上传文件相关的资料

热点内容
手机包书网txt电子书 浏览:477
驯龙骑士2免费观看 浏览:442
台湾r 浏览:442
看片用哪个云盘 浏览:404
类似五十度灰的电影 浏览:584
韩国穿越时空的电影 浏览:843
主角是长不大的小正太 浏览:707
微信如何发定期文件 浏览:970
ug文件转cad 浏览:570
电影开头女主在做瑜伽 浏览:269
小米的玩具米佩婷 浏览:119
苏州电影院时间查询 浏览:734
上杭电影院今日电影票 浏览:410
邵氏古龙电影全集 浏览:19
日本宅男影片 浏览:440
r903升级 浏览:974
韩国论理 片 文艺推荐 浏览:891
夜雨三部曲倪楠 浏览:293
泰州哪里有学习少儿编程的 浏览:357
上海大数据交易所股东 浏览:42

友情链接