spring mvc restful能上传多大文件

spring mvc restful能上传多大文件,第1张

SpringMVC本身对Restful支持非常好。它的@RequestMapping、@RequestParam、@PathVariable、@ResponseBody注解很好的支持了REST。18.2CreatingRESTfulservices1.@RequestMappingSpringusesthe@RequestMappingmethodannotationtodefinetheURITemplatefortherequest.类似于struts的action-mapping。可以指定POST或者GET。2.@PathVariableThe@PathVariablemethodparameterannotationisusedtoindicatethatamethodparametershouldbeboundtothevalueofaURItemplatevariable.用于抽取URL中的信息作为参数。(注意,不包括请求字符串,那是@RequestParam做的事情。)@RequestMapping("/owners/{ownerId}",method=RequestMethod.GET)publicStringfindOwner(@PathVariableStringownerId,Modelmodel){//}如果变量名与pathVariable名不一致,那么需要指定:@RequestMapping("/owners/{ownerId}",method=RequestMethod.GET)publicStringfindOwner(@PathVariable("ownerId")StringtheOwner,Modelmodel){//implementationomitted}Tipmethodparametersthataredecoratedwiththe@PathVariableannotationcanbeofanysimpletypesuchasint,long,DateSpringautomaticallyconvertstotheappropriatetypeandthrowsaTypeMismatchExceptionifthetypeisnotcorrect.3.@RequestParam官方文档居然没有对这个注解进行说明,估计是遗漏了(真不应该啊)。这个注解跟@PathVariable功能差不多,只是参数值的来源不一样而已。它的取值来源是请求参数(querystring或者post表单字段)。对了,因为它的来源可以是POST字段,所以它支持更丰富和复杂的类型信息。比如文件对象:@RequestMapping("/imageUpload")publicStringprocessImageUpload(@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")publicStringprocessImageUpload(@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)。publicinterfaceHttpMessageConverter{//Indicatewhetherthegivenclassissupportedbythisconverter.booleansupports(Classclazz)//ReturnthelistofMediaTypeobjectssupportedbythisconverter.ListgetSupportedMediaTypes()//Readanobjectofthegiventypeformthegiveninputmessage,andreturnsit.Tread(Classclazz,HttpInputMessageinputMessage)throwsIOException,HttpMessageNotReadableException//Writeangivenobjecttothegivenoutputmessage.voidwrite(Tt,HttpOutputMessageoutputMessage)throwsIOException,HttpMessageNotWritableException}SpringMVC对HttpMessageConverter有多种默认实现,基本上不需要自己再自定义HttpMessageConverterStringHttpMessageConverter-convertsstringsFormHttpMessageConverter-convertsformdatato/fromaMultiValueMapByteArrayMessageConverter-convertsbytearraysSourceHttpMessageConverter-convertto/fromajavax.xml.transform.SourceRssChannelHttpMessageConverter-convertto/fromRSSfeedsMappingJacksonHttpMessageConverter-convertto/fromJSONusingJackson'sObjectMapperetc然而对于RESTful应用,用的最多的当然是MappingJacksonHttpMessageConverter。但是MappingJacksonHttpMessageConverter不是默认的HttpMessageConverter:publicclassAnnotationMethodHandlerAdapterextendsWebContentGeneratorimplementsHandlerAdapter,Ordered,BeanFactoryAware{publicAnnotationMethodHandlerAdapter(){//norestrictionofHTTPmethodsbydefaultsuper(false)//SeeSPR-7316StringHttpMessageConverterstringHttpMessageConverter=newStringHttpMessageConverter()stringHttpMessageConverter.setWriteAcceptCharset(false)this.messageConverters=newHttpMessageConverter[]{newByteArrayHttpMessageConverter(),stringHttpMessageConverter,newSourceHttpMessageConverter(),newXmlAwareFormHttpMessageConverter()}}}如上:默认的HttpMessageConverter是ByteArrayHttpMessageConverter、stringHttpMessageConverter、SourceHttpMessageConverter和XmlAwareFormHttpMessageConverter转换器。所以需要配置一下:text/plaincharset=GBK配置好了之后,就可以享受@Requestbody和@ResponseBody对JONS转换的便利之处了:@RequestMapping(value="api",method=RequestMethod.POST)@ResponseBodypublicbooleanaddApi(@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.utilimportjava.io.IOExceptionimportjava.io.PrintStreamimportorg.codehaus.jackson.map.ObjectMapperimportorg.codehaus.jackson.map.annotate.JsonSerialize.Inclusionimportorg.springframework.http.HttpOutputMessageimportorg.springframework.http.converter.HttpMessageNotWritableExceptionimportorg.springframework.http.converter.json.MappingJacksonHttpMessageConverterimportorg.springframework.web.context.request.RequestAttributesimportorg.springframework.web.context.request.RequestContextHolderimportorg.springframework.web.context.request.ServletRequestAttributespublicclassMappingJsonpHttpMessageConverterextendsMappingJacksonHttpMessageConverter{publicMappingJsonpHttpMessageConverter(){ObjectMapperobjectMapper=newObjectMapper()objectMapper.setSerializationConfig(objectMapper.getSerializationConfig().withSerializationInclusion(Inclusion.NON_NULL))setObjectMapper(objectMapper)}@OverrideprotectedvoidwriteInternal(Objecto,HttpOutputMessageoutputMessage)throwsIOException,HttpMessageNotWritableException{StringjsonpCallback=nullRequestAttributesreqAttrs=RequestContextHolder.currentRequestAttributes()if(reqAttrsinstanceofServletRequestAttributes){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(")")}}}

在使用springmvc提供rest接口实现文件上传时,有时为了测试需要使用RestTemplate进行调用,那么在使用RestTemplate调用文件上传接口时有什么特别的地方呢?实际上只需要注意一点就行了,就是创建文件资源时需要使用org.springframework.core.io.FileSystemResource类,而不能直接使用Java.io.File对象。

Controller中的rest接口代码如下:

[java] view plain copy

@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 copy

@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 copy

String string = rest.postForObject(url, param, String.class)

可以换成:

[java] view plain copy

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())


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/11997741.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存