我想发送一些字符串到后端服务器。我没有使用json与multipart,我使用了请求参数。
@RequestMapping(value = "/upload", method = RequestMethod.POST) public void uploadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam("uuid") String uuid, @RequestParam("type") DocType type, @RequestParam("file") MultipartFile uploadfile)
网址看起来像
http://localhost:8080/file/upload?uuid=46f073d0&type=PASSPORT
我正在传递两个参数(uuid和type)以及文件上传。 希望这将有助于谁没有复杂的json数据发送。
我知道这个帖子很老了,但是,我在这里缺少一个选项。如果您要将要发送的元数据(以任何格式)与要上载的数据一起发送,则可以制作单个元数据 multipart/related 请求。
multipart/related
Multipart / Related媒体类型适用于由多个相互关联的身体部位组成的复合对象。
你可以检查一下 RFC 2387 更深入细节的规范。
基本上,这种请求的每个部分可以具有不同类型的内容,并且所有部分以某种方式相关(例如,图像和它的元数据)。部件由边界字符串标识,最后的边界字符串后跟两个连字符。
的 例: 强>
POST /upload HTTP/1.1 Host: www.hostname.com Content-Type: multipart/related; boundary=xyz Content-Length: [actual-content-length] --xyz Content-Type: application/json; charset=UTF-8 { "name": "Sample image", "desc": "...", ... } --xyz Content-Type: image/jpeg [image data] [image data] [image data] ... --foo_bar_baz--
FormData对象:使用Ajax上传文件
XMLHttpRequest Level 2增加了对新FormData接口的支持。 FormData对象提供了一种方法,可以轻松构造一组表示表单字段及其值的键/值对,然后可以使用XMLHttpRequest send()方法轻松发送。
function AjaxFileUpload() { var file = document.getElementById("files"); //var file = fileInput; var fd = new FormData(); fd.append("imageFileData", file); var xhr = new XMLHttpRequest(); xhr.open("POST", '/ws/fileUpload.do'); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { alert('success'); } else if (uploadResult == 'success') alert('error'); }; xhr.send(fd); }
https://developer.mozilla.org/en-US/docs/Web/API/FormData
如果您正在开发休息服务器,则可以执行此操作
{"file_url":"http://cockwombles.com/blah.jpg"}
@RequestMapping(value = "/uploadImageJson", method = RequestMethod.POST) public @ResponseBody Object jsongStrImage(@RequestParam(value="image") MultipartFile image, @RequestParam String jsonStr) { -- use com.fasterxml.jackson.databind.ObjectMapper convert Json String to Object }
我知道这个问题已经过时了,但在最后几天我搜索了整个网络以解决同样的问题。我有grails REST webservices和iPhone Client发送图片,标题和描述。
我不知道我的方法是否最好,但是如此简单易行。
我使用UIImagePickerController拍照并使用请求的标头标签向服务器发送NSData以发送图片的数据。
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myServerAddress"]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)]; [request setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"]; [request setValue:@"myPhotoTitle" forHTTPHeaderField:@"Photo-Title"]; [request setValue:@"myPhotoDescription" forHTTPHeaderField:@"Photo-Description"]; NSURLResponse *response; NSError *error; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
在服务器端,我使用以下代码收到照片:
InputStream is = request.inputStream def receivedPhotoFile = (IOUtils.toByteArray(is)) def photo = new Photo() photo.photoFile = receivedPhotoFile //photoFile is a transient attribute photo.title = request.getHeader("Photo-Title") photo.description = request.getHeader("Photo-Description") photo.imageURL = "temp" if (photo.save()) { File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile() saveLocation.mkdirs() File tempFile = File.createTempFile("photo", ".jpg", saveLocation) photo.imageURL = saveLocation.getName() + "/" + tempFile.getName() tempFile.append(photo.photoFile); } else { println("Error") }
我不知道将来是否有问题,但现在在生产环境中工作正常。
请确保您有以下导入。当然其他标准进口
import org.springframework.core.io.FileSystemResource void uploadzipFiles(String token) { RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000) def zipFile = new File("testdata.zip") def Id = "001G00000" MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>() form.add("id", id) form.add('file',new FileSystemResource(zipFile)) def urld ='''http://URL'''; def resp = rest.post(urld) { header('X-Auth-Token', clientSecret) contentType "multipart/form-data" body(form) } println "resp::"+resp println "resp::"+resp.text println "resp::"+resp.headers println "resp::"+resp.body println "resp::"+resp.status }
我在这里问了一个类似的问题:
如何使用REST Web服务上载包含元数据的文件?
你基本上有三个选择:
multipart/form-data
您可以使用以下命令在一个请求中发送文件和数据 多部分/格式数据 内容类型:
在许多应用中,可以向用户呈现 表单。用户将填写表格,包括信息 是键入的,由用户输入生成,或包含在文件中 用户已选择。填写表格时,数据来自 表单从用户发送到接收应用程序。 MultiPart / Form-Data的定义来自其中一个 应用...
在许多应用中,可以向用户呈现 表单。用户将填写表格,包括信息 是键入的,由用户输入生成,或包含在文件中 用户已选择。填写表格时,数据来自 表单从用户发送到接收应用程序。
MultiPart / Form-Data的定义来自其中一个 应用...
从 http://www.faqs.org/rfcs/rfc2388.html :
“multipart / form-data”包含一系列部分。每个部分都是 期望包含内容处置标题[RFC 2183]其中 处置类型是“表单数据”,并且处置包含 (name)的(附加)参数,其中的值 parameter是表单中的原始字段名称。例如,一部分 可能包含标题: 内容处理:表格数据;名称=“用户” 具有与“user”字段的条目对应的值。
“multipart / form-data”包含一系列部分。每个部分都是 期望包含内容处置标题[RFC 2183]其中 处置类型是“表单数据”,并且处置包含 (name)的(附加)参数,其中的值 parameter是表单中的原始字段名称。例如,一部分 可能包含标题:
内容处理:表格数据;名称=“用户”
具有与“user”字段的条目对应的值。
您可以在边界之间的每个部分中包含文件信息或字段信息。我已经成功实现了RESTful服务,该服务要求用户提交数据和表单,并且multipart / form-data完美地工作。该服务是使用Java / Spring构建的,客户端使用的是C#,所以很遗憾,我没有任何Grails示例可以为您提供有关如何设置服务的信息。在这种情况下,您不需要使用JSON,因为每个“form-data”部分都为您提供了指定参数名称及其值的位置。
使用multipart / form-data的好处在于您使用的是HTTP定义的头文件,因此您坚持使用现有HTTP工具创建服务的REST理念。