resttemplate post怎么传multipartfile

| 漏洞检测 |
| 隐藏捆绑 |
在HTML中使用WCF RESTful上传文件
说明 在HTML中上传文件时会为文件内容加入一头一尾,使用浏览器自带的调试工具可看到请求头中有Request Payload数据如下所示: [plain] -----------------------8cc0b8cfcfd5ed2 Content-Disposition: form- name= filename=item3.xml Content-Typ
在中时会为内容加入一头一尾,浏览器自带的调试工具可看到请求头中有Request Payload数据如下所示:
-----------------------8cc0b8cfcfd5ed2&
Content-Disposition: form- name=&file&; filename=&item3.xml&&
Content-Type: application/octet-stream&
这里是真正的文件内容&
-----------------------8cc0b8cfcfd5ed2--&
-----------------------8cc0b8cfcfd5ed2
Content-Disposition: form- name=&file&; filename=&item3.xml&
Content-Type: application/octet-stream
这里是真正的文件内容
-----------------------8cc0b8cfcfd5ed2--
因此服务端接收后要手动对其作解析。
&!DOCTYPE &&
&&& &meta http-equiv=&Content-Type& content=&text/ charset=utf8& /&&
&&& &meta http-equiv=&pragma& content=&no-cache& /&&
&&& &title&测试页&/title&&
&&& 文件页&
&&&&&&& &form action=&:4513/IVisitorRestService/Upload/utf-8& method=&POST& enctype=&multipart/form-data&&&
&&&&&&&&&&& &input type=&file& name=&fileContent& /&&!--这里的name属性必须有,否则浏览器不会将其作为表单内容进行提交--&&
&&&&&&&&&&& &input type=&submit& /&&
&&&&&&& &/form&&
&!DOCTYPE HTML&
&&& &meta http-equiv=&Content-Type& content=&text/ charset=utf8& /&
&&& &meta http-equiv=&pragma& content=&no-cache& /&
&&& &title&测试页&/title&
&&& 文件上传页
&&&&&&& &form action=&:4513/IVisitorRestService/Upload/utf-8& method=&POST& enctype=&multipart/form-data&&
&&&&&&&&&&& &input type=&file& name=&fileContent& /&&!--这里的name属性必须有,否则浏览器不会将其作为表单内容进行提交--&
&&&&&&&&&&& &input type=&submit& /&
&&&&&&& &/form&
/// &summary&&&
/// HTML上传文件&&
/// &/summary&&&
/// &param name=&file&&文件流&/param&&&
/// &param name=&encodingName&&HTML的文字编码名&/param&&&
[WebInvoke(Method = &POST&, UriTemplate = &Upload/{encodingName}&)]&
void Upload(Stream file, string encodingName);&
/// &summary&
/// 使用HTML上传文件
/// &/summary&
/// &param name=&file&&文件流&/param&
/// &param name=&encodingName&&HTML的文字编码名&/param&
[WebInvoke(Method = &POST&, UriTemplate = &Upload/{encodingName}&)]
void Upload(Stream file, string encodingName);
public void Upload(Stream file, string encodingName)&
&&& using (var ms = new MemoryStream())&
&&&&&&& file.CopyTo(ms);&
&&&&&&& ms.Position = 0;&
&&&&&&& var encoding = Encoding.GetEncoding(encodingName);&
&&&&&&& var reader = new StreamReader(ms, encoding);&
&&&&&&& var headerLength = 0L;&
&&&&&&& //读取第一行&&
&&&&&&& var firstLine = reader.ReadLine();&
&&&&&&& //计算偏移(字符串长度+回车换行2个字符)&&
&&&&&&& headerLength += encoding.GetBytes(firstLine).LongLength + 2;&
&&&&&&& //读取第二行&&
&&&&&&& var secondLine = reader.ReadLine();&
&&&&&&& //计算偏移(字符串长度+回车换行2个字符)&&
&&&&&&& headerLength += encoding.GetBytes(secondLine).LongLength + 2;&
&&&&&&& //解析文件名&&
&&&&&&& var fileName = new System.Text.RegularExpressions.Regex(&filename=\&(?&fn&.*)\&&).Match(secondLine).Groups[&fn&].V&
&&&&&&& //一直读到空行为止&&
&&&&&&& while (true)&
&&&&&&& {&
&&&&&&&&&&& //读取一行&&
&&&&&&&&&&& var line = reader.ReadLine();&
&&&&&&&&&&& //若到头,则直接返回&&
&&&&&&&&&&& if (line == null)&
&&&&&&&&&&&&&&&&
&&&&&&&&&&& //若未到头,则计算偏移(字符串长度+回车换行2个字符)&&
&&&&&&&&&&& headerLength += encoding.GetBytes(line).LongLength + 2;&
&&&&&&&&&&& if (line == &&)&
&&&&&&&&&&&&&&&&
&&&&&&& }&
&&&&&&& //设置偏移,以开始读取文件内容&&
&&&&&&& ms.Position = headerL&
&&&&&&& ////减去末尾的字符串:&\r\n--\r\n&&&
&&&&&&& ms.SetLength(ms.Length - encoding.GetBytes(firstLine).LongLength - 3 * 2);&
&&&&&&& using (var fileToupload = new FileStream(&D:\\FileUpload\\& + fileName, FileMode.Create))&
&&&&&&& {&
&&&&&&&&&&& ms.CopyTo(fileToupload);&
&&&&&&&&&&& fileToupload.Close();&
&&&&&&&&&&& fileToupload.Dispose();&
&&&&&&& }&
(责任编辑:幽灵学院)
------分隔线----------------------------
2.2.2 路由注册 ASP.NET MVC通过调用代表全局路由表的RouteCollection对象的扩展方法M...
这里以Mvc3模版项目的登录页为例,简单说一下过程: 首先准备资源文件,即语言包。为w...
一,使用InvokeMember 思路:在类型的type的对象上调用InvokeMember方法,传递要在其...
一:随便看看几个razor语法 1. 你要会用 单行和代码块语法输出 1 h1 2 第一种方式:/h1...
public class CsvFileResult : FileResult where T : class{private IEnumerable _dat...
昨天在写代码中一不小心将UserControl写成了Control,将原来应该继承自System.Web.UI....
admin@1744.cc
工作日:9:00-21:00
周 六:9:00-18:00
&&扫一扫关注幽灵学院
广告服务:QQ:8094人阅读
java(22)
在使用springmvc提供rest接口实现文件上传时,有时为了测试需要使用RestTemplate进行调用,那么在使用RestTemplate调用文件上传接口时有什么特别的地方呢?实际上只需要注意一点就行了,就是创建文件资源时需要使用org.springframework.core.io.FileSystemResource类,而不能直接使用java.io.File对象。
Controller中的rest接口代码如下:
@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);
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测试上传代码如下:
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);
String string = rest.postForObject(url, param, String.class);可以换成:
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());
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:312054次
积分:4997
积分:4997
排名:第3405名
原创:60篇
译文:19篇
评论:98条
(2)(4)(8)(1)(1)(3)(3)(2)(1)(1)(1)(7)(6)(9)(1)(1)(6)(6)(10)(2)(1)(2)(1)(2)(2)摘记RestTemplate的集成测试类
&来源:读书人网&【读书人网():综合教育门户网站】
摘录RestTemplate的集成测试类/* 2.* Copyright
the original author or authors. 3.* 4.* Lice
摘录RestTemplate的集成测试类
/* 2.&&& * Copyright
the original author or authors. 3.&&& * 4.&&& * Licensed under the Apache License, Version 2.0 (the "License"); 5.&&& * you may not use this file except in compliance with the License. 6.&&& * You may obtain a copy of the License at 7.&&& * 8.&&& *&&&&& http://www.apache.org/licenses/LICENSE-2.0 9.&&& * 10.&&& * Unless required by applicable law or agreed to in writing, software 11.&&& * distributed under the License is distributed on an "AS IS" BASIS, 12.&&& * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13.&&& * See the License for the specific language governing permissions and 14.&&& * limitations under the License. 15.&&& */ 16. 17.&& package org.springframework.web. 18.&& 19.&& import java.io.IOE 20.&& import java.io.UnsupportedEncodingE 21.&& import java.net.URI; 22.&& import java.net.URISyntaxE 23.&& import java.nio.charset.C 24.&& import java.util.C 25.&& import java.util.EnumS 26.&& import java.util.L 27.&& import java.util.S 28.&& import javax.servlet.GenericS 29.&& import javax.servlet.ServletE 30.&& import javax.servlet.ServletR 31.&& import javax.servlet.ServletR 32.&& import javax.servlet.http.HttpS 33.&& import javax.servlet.http.HttpServletR 34.&& import javax.servlet.http.HttpServletR 35.&& 36.&& import mons.fileupload.FileI 37.&& import mons.fileupload.FileItemF 38.&& import mons.fileupload.FileUploadE 39.&& import mons.fileupload.disk.DiskFileItemF 40.&& import mons.fileupload.servlet.ServletFileU 41.&& import org.junit.AfterC 42.&& import org.junit.B 43.&& import org.junit.BeforeC 44.&& import org.junit.T 45.&& import org.mortbay.jetty.S 46.&& import org.mortbay.jetty.servlet.C 47.&& import org.mortbay.jetty.servlet.ServletH 48.&& 49.&& import org.springframework.core.io.ClassPathR 50.&& import org.springframework.core.io.R 51.&& import org.springframework.http.HttpE 52.&& import org.springframework.http.HttpH 53.&& import org.springframework.http.HttpM 54.&& import org.springframework.http.HttpS 55.&& import org.springframework.http.MediaT 56.&& import org.springframework.http.ResponseE 57.&& import org.springframework.monsClientHttpRequestF 58.&& import org.springframework.http.client.FreePortS 59.&& import org.springframework.util.FileCopyU 60.&& import org.springframework.util.LinkedMultiValueM 61.&& import org.springframework.util.MultiValueM 62.&& 63.&& import static org.junit.Assert.*; 64.&& 65.&& /** @author Arjen Poutsma */ 66.&& public class RestTemplateIntegrationTests { 67.&& 68.&& private RestT 69.&& 70.&& private static Server jettyS 71.&& 72.&& private static String helloWorld = "H\u00e9llo W\u00f6rld"; 73.&& 74.&& private static String baseU 75.&& 76.&& private static MediaType contentT 77.&& 78.&& @BeforeClass 79.&& public static void startJettyServer() throws Exception { 80.&& int port = FreePortScanner.getFreePort(); 81.&& jettyServer = new Server(port); 82.&& baseUrl = "http://localhost:" + 83.&& Context jettyContext = new Context(jettyServer, "/"); 84.&& byte[] bytes = helloWorld.getBytes("UTF-8"); 85.&& contentType = new MediaType("text", "plain", Collections.singletonMap("charset", "utf-8")); 86.&& jettyContext.addServlet(new ServletHolder(new GetServlet(bytes, contentType)), "/get"); 87.&& jettyContext.addServlet(new ServletHolder(new GetServlet(new byte[0], contentType)), "/get/nothing"); 88.&& jettyContext.addServlet( 89.&& new ServletHolder(new PostServlet(helloWorld, baseUrl + "/post/1", bytes, contentType)), 90.&& "/post"); 91.&& jettyContext.addServlet(new ServletHolder(new ErrorServlet(404)), "/errors/notfound"); 92.&& jettyContext.addServlet(new ServletHolder(new ErrorServlet(500)), "/errors/server"); 93.&& jettyContext.addServlet(new ServletHolder(new UriServlet()), "/uri/*"); 94.&& jettyContext.addServlet(new ServletHolder(new MultipartServlet()), "/multipart"); 95.&& jettyServer.start(); 96.&& } 97.&& 98.&& @Before 99.&& public void createTemplate() { 100.&& template = new RestTemplate(new CommonsClientHttpRequestFactory()); 101.&& } 102.&& 103.&& @AfterClass 104.&& public static void stopJettyServer() throws Exception { 105.&& if (jettyServer != null) { 106.&& jettyServer.stop(); 107.&& } 108.&& } 109.&& 110.&& @Test 111.&& public void getString() { 112.&& String s = template.getForObject(baseUrl + "/{method}", String.class, "get"); 113.&& assertEquals("Invalid content", helloWorld, s); 114.&& } 115.&& 116.&& @Test 117.&& public void getEntity() { 118.&& ResponseEntity&String& entity = template.getForEntity(baseUrl + "/{method}", String.class, "get"); 119.&& assertEquals("Invalid content", helloWorld, entity.getBody()); 120.&& assertFalse("No headers", entity.getHeaders().isEmpty()); 121.&& assertEquals("Invalid content-type", contentType, entity.getHeaders().getContentType()); 122.&& assertEquals("Invalid status code", HttpStatus.OK, entity.getStatusCode()); 123.&& } 124.&& 125.&& @Test 126.&& public void getNoResponse() { 127.&& String s = template.getForObject(baseUrl + "/get/nothing", String.class); 128.&& assertEquals("Invalid content", "", s); 129.&& } 130.&& 131.&& @Test 132.&& public void postForLocation() throws URISyntaxException { 133.&& URI location = template.postForLocation(baseUrl + "/{method}", helloWorld, "post"); 134.&& assertEquals("Invalid location", new URI(baseUrl + "/post/1"), location); 135.&& } 136.&& 137.&& @Test 138.&& public void postForLocationEntity() throws URISyntaxException { 139.&& HttpHeaders entityHeaders = new HttpHeaders(); 140.&& entityHeaders.setContentType(new MediaType("text", "plain", Charset.forName("ISO-8859-15"))); 141.&& HttpEntity&String& entity = new HttpEntity&String&(helloWorld, entityHeaders); 142.&& URI location = template.postForLocation(baseUrl + "/{method}", entity, "post"); 143.&& assertEquals("Invalid location", new URI(baseUrl + "/post/1"), location); 144.&& } 145.&& 146.&& @Test 147.&& public void postForObject() throws URISyntaxException { 148.&& String s = template.postForObject(baseUrl + "/{method}", helloWorld, String.class, "post"); 149.&& assertEquals("Invalid content", helloWorld, s); 150.&& } 151.&& 152.&& @Test 153.&& public void notFound() { 154.&& try { 155.&& template.execute(baseUrl + "/errors/notfound", HttpMethod.GET, null, null); 156.&& fail("HttpClientErrorException expected"); 157.&& } 158.&& catch (HttpClientErrorException ex) { 159.&& assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode()); 160.&& assertNotNull(ex.getStatusText()); 161.&& assertNotNull(ex.getResponseBodyAsString()); 162.&& } 163.&& } 164.&& 165.&& @Test 166.&& public void serverError() { 167.&& try { 168.&& template.execute(baseUrl + "/errors/server", HttpMethod.GET, null, null); 169.&& fail("HttpServerErrorException expected"); 170.&& } 171.&& catch (HttpServerErrorException ex) { 172.&& assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ex.getStatusCode()); 173.&& assertNotNull(ex.getStatusText()); 174.&& assertNotNull(ex.getResponseBodyAsString()); 175.&& } 176.&& } 177.&& 178.&& @Test 179.&& public void optionsForAllow() throws URISyntaxException { 180.&& Set&HttpMethod& allowed = template.optionsForAllow(new URI(baseUrl + "/get")); 181.&& assertEquals("Invalid response", 182.&& EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD, HttpMethod.TRACE), allowed); 183.&& } 184.&& 185.&& @Test 186.&& public void uri() throws InterruptedException, URISyntaxException { 187.&& String result = template.getForObject(baseUrl + "/uri/{query}", String.class, "Z\u00fcrich"); 188.&& assertEquals("Invalid request URI", "/uri/Z%C3%BCrich", result); 189.&& 190.&& result = template.getForObject(baseUrl + "/uri/query={query}", String.class, "foo@bar"); 191.&& assertEquals("Invalid request URI", "/uri/query=foo@bar", result); 192.&& 193.&& result = template.getForObject(baseUrl + "/uri/query={query}", String.class, "T\u014dky\u014d"); 194.&& assertEquals("Invalid request URI", "/uri/query=T%C5%8Dky%C5%8D", result); 195.&& } 196.&& 197.&& @Test 198.&& public void multipart() throws UnsupportedEncodingException { 199.&& MultiValueMap&String, Object& parts = new LinkedMultiValueMap&String, Object&(); 200.&& parts.add("name 1", "value 1"); 201.&& parts.add("name 2", "value 2+1"); 202.&& parts.add("name 2", "value 2+2"); 203.&& Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg"); 204.&& parts.add("logo", logo); 205.&& 206.&& template.postForLocation(baseUrl + "/multipart", parts); 207.&& } 208.&& 209.&& @Test 210.&& public void exchangeGet() throws Exception { 211.&& HttpHeaders requestHeaders = new HttpHeaders(); 212.&& requestHeaders.set("MyHeader", "MyValue"); 213.&& HttpEntity&?& requestEntity = new HttpEntity(requestHeaders); 214.&& ResponseEntity&String& response = 215.&& template.exchange(baseUrl + "/{method}", HttpMethod.GET, requestEntity, String.class, "get"); 216.&& assertEquals("Invalid content", helloWorld, response.getBody()); 217.&& } 218.&& 219.&& @Test 220.&& public void exchangePost() throws Exception { 221.&& HttpHeaders requestHeaders = new HttpHeaders(); 222.&& requestHeaders.set("MyHeader", "MyValue"); 223.&& requestHeaders.setContentType(MediaType.TEXT_PLAIN); 224.&& HttpEntity&String& requestEntity = new HttpEntity&String&(helloWorld, requestHeaders); 225.&& HttpEntity&?& result = template.exchange(baseUrl + "/{method}", HttpMethod.POST, requestEntity, null, "post"); 226.&& assertEquals("Invalid location", new URI(baseUrl + "/post/1"), result.getHeaders().getLocation()); 227.&& assertFalse(result.hasBody()); 228.&& } 229.&& 230.&& /** Servlet that returns and error message for a given status code. */ 231.&& private static class ErrorServlet extends GenericServlet { 232.&& 233.&&
234.&& 235.&& private ErrorServlet(int sc) { 236.&& this.sc = 237.&& } 238.&& 239.&& @Override 240.&& public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { 241.&& ((HttpServletResponse) response).sendError(sc); 242.&& } 243.&& } 244.&& 245.&& private static class GetServlet extends HttpServlet { 246.&& 247.&& private final byte[] 248.&& 249.&& private final MediaType contentT 250.&& 251.&& private GetServlet(byte[] buf, MediaType contentType) { 252.&& this.buf = 253.&& this.contentType = contentT 254.&& } 255.&& 256.&& @Override 257.&& protected void doGet(HttpServletRequest request, HttpServletResponse response) 258.&& throws ServletException, IOException { 259.&& response.setContentType(contentType.toString()); 260.&& response.setContentLength(buf.length); 261.&& FileCopyUtils.copy(buf, response.getOutputStream()); 262.&& } 263.&& } 264.&& 265.&& private static class PostServlet extends HttpServlet { 266.&& 267.&& private final S 268.&& 269.&& private final S 270.&& 271.&& private final byte[] 272.&& 273.&& private final MediaType contentT 274.&& 275.&& private PostServlet(String s, String location, byte[] buf, MediaType contentType) { 276.&& this.s = 277.&& this.location = 278.&& this.buf = 279.&& this.contentType = contentT 280.&& } 281.&& 282.&& @Override 283.&& protected void doPost(HttpServletRequest request, HttpServletResponse response) 284.&& throws ServletException, IOException { 285.&& assertTrue("Invalid request content-length", request.getContentLength() & 0); 286.&& assertNotNull("No content-type", request.getContentType()); 287.&& String body = FileCopyUtils.copyToString(request.getReader()); 288.&& assertEquals("Invalid request body", s, body); 289.&& response.setStatus(HttpServletResponse.SC_CREATED); 290.&& response.setHeader("Location", location); 291.&& response.setContentLength(buf.length); 292.&& response.setContentType(contentType.toString()); 293.&& FileCopyUtils.copy(buf, response.getOutputStream()); 294.&& } 295.&& } 296.&& 297.&& private static class UriServlet extends HttpServlet { 298.&& 299.&& @Override 300.&& protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 301.&& resp.setContentType("text/plain"); 302.&& resp.setCharacterEncoding("UTF-8"); 303.&& resp.getWriter().write(req.getRequestURI()); 304.&& } 305.&& } 306.&& 307.&& private static class MultipartServlet extends HttpServlet { 308.&& 309.&& @Override 310.&& protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 311.&& assertTrue(ServletFileUpload.isMultipartContent(req)); 312.&& FileItemFactory factory = new DiskFileItemFactory(); 313.&& ServletFileUpload upload = new ServletFileUpload(factory); 314.&& try { 315.&& List items = upload.parseRequest(req); 316.&& assertEquals(4, items.size()); 317.&& FileItem item = (FileItem) items.get(0); 318.&& assertTrue(item.isFormField()); 319.&& assertEquals("name 1", item.getFieldName()); 320.&& assertEquals("value 1", item.getString()); 321.&& 322.&& item = (FileItem) items.get(1); 323.&& assertTrue(item.isFormField()); 324.&& assertEquals("name 2", item.getFieldName()); 325.&& assertEquals("value 2+1", item.getString()); 326.&& 327.&& item = (FileItem) items.get(2); 328.&& assertTrue(item.isFormField()); 329.&& assertEquals("name 2", item.getFieldName()); 330.&& assertEquals("value 2+2", item.getString()); 331.&& 332.&& item = (FileItem) items.get(3); 333.&& assertFalse(item.isFormField()); 334.&& assertEquals("logo", item.getFieldName()); 335.&& assertEquals("logo.jpg", item.getName()); 336.&& assertEquals("image/jpeg", item.getContentType()); 337.&& } 338.&& catch (FileUploadException ex) { 339.&& throw new ServletException(ex); 340.&& } 341.&& 342.&& } 343.&& } 344.&& 345.&& } [color=darkred][/color]}

我要回帖

更多关于 spring4 resttemplate 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信