使用java中的Restlet multipart / form-data上传文件
所以我现在搜索了相当多的示例代码,但我发现的唯一的事情是服务器端的示例,这意味着接收部分 。
我想创建一个应用程序,它使用restlet上传文件,内容类型: multipart/form-data
。 所以我需要发送部分
如何为此创建表单?
我尝试的是以下,但它不起作用:
public void UploadFile(File f){ Form fileForm = new Form(); fileForm.add(Disposition.NAME_FILENAME, "test.jpg"); Disposition disposition = new Disposition(Disposition.TYPE_INLINE, fileForm); FileRepresentation entity = new FileRepresentation(f, MediaType.IMAGE_ALL); entity.setDisposition(disposition); FormData fd = new FormData("photo", entity); FormDataSet fds = new FormDataSet(); fds.setMultipart(true); fds.setMediaType(MediaType.MULTIPART_FORM_DATA); fds.getEntries().add(fd); String url = "http://localhost/uploadFile"; Optional opJrep = m_RestClient.postJson(url,fds,MediaType.MULTIPART_FORM_DATA, Optional.empty()); }
使用以下方法发布表单并接收JSON表示(postJson表示post,get json back)
public Optional postJson(String url, Object sendObject,MediaType mediaType,Optional<Collection> headers){ //build resource ClientResource resource = new ClientResource(url); //build request with headers Request request = new Request(Method.POST,url); headers.ifPresent(col->{ request.getHeaders().addAll(col); }); //set request resource.setRequest(request); //get response resource.post(sendObject,mediaType); Representation responseEntity = resource.getResponseEntity(); System.out.println(responseEntity.toString()); try { //get json representation JsonRepresentation json = new JsonRepresentation(responseEntity); return Optional.of(json); } catch (Exception e) { } return Optional.empty(); }
当一切正常时,接收服务器应该返回一个JSON字符串。
实际上,端点不是我的本地主机,而是带有SendPhoto方法的Telegram Bot。 在那里,您可以使用multipart / form-data将文件作为图像发布
SendPhoto文档
我该怎么办? 如何使用restlet作为multipart / form-data上传文件(在我的情况下为图像)?
我用FormDataSet
做了一些尝试和错误编程并得到了结果。
要使用restlet上传文件(在本例中为图片),您必须执行以下操作:
FileRepresentation entity = new FileRepresentation(file, mediaType); //create the fileRepresentation FormDataSet fds = new FormDataSet(); //create the FormDataSet FormData fd = new FormData(key, entity); //create the Formdata using a key and a value (file) fds.getEntries().add(fd); //add the form data to the set fds.setMultipart(true); //set the multipart value to true String url = "http://localhost/uploadPhoto"; Optional opJrep = m_RestClient.postJson(url,fds,MediaType.MULTIPART_FORM_DATA, Optional.empty());
此示例使用与问题中描述的相同的postJson
方法。
- 使用Struts上传图像
- 使用MultipartFile在Spring Boot中无法上传多个文件,从JSP中获取Controller中的空数组
- 从Java / J2EE应用程序将文件上载到SharePoint
- 获取HTTP状态400 – 必需的MultipartFile参数’file’在spring中不存在
- j2ee primefaces fileupload文件保存目标
- Resteasy和fileupload:没有内容处理错误
- Java Http Client通过POST上传文件
- 在struts1中上传文件
- Spring MVC – AngularJS – 文件上传 – org.apache.commons.fileupload.FileUploadException