Alfresco – 如何在使用 RestTemplate 进行 POST 请求时添加/设置文件内容

huangapple go评论75阅读模式
英文:

Alfresco - How to add/set content of the file while doing post using RestTemplate

问题

我正尝试使用以下方法将文件上传到DocLibrary文件夹:

private static void postTheDocument() {
    final String restENDPoint = "http://servername:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/48eea6b2-fe9b-4cd2-8270-5caa35d7e8dc/children";
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setBasicAuth("admin", "admin");
    String requestJson = "{\"name\": \"TestName123s.doc\",\"nodeType\": \"hr:HR_Type\",\"properties\":{\"cm:title\":\"New Test title123\",\"hr:emp_no\":\"123456\",\"hr:lname\":\"Last_Name1\",\"hr:fname\":\"First_Name1\"}}";
    HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
    HttpEntity<String> response = restTemplate.exchange(restENDPoint, HttpMethod.POST, entity, String.class);
    System.out.println(response.getBody().toString());
}

文档建议使用以下curl命令:

curl -utest:test -X POST host:port/alfresco/api/-default-/public/alfresco/versions/1/nodes/12341234-2344-2344-43243242334/children -F filedata=@test.txt

使用postTheDocument()方法创建了空白文档。但当我尝试以下请求时:

String requestJson = "{\"filedata\": \"@Z:/05test/YYYYest11qq890.pdf\",\"name\": \"TestName123s.doc\",\"nodeType\": \"hr:HR_Type\",\"properties\":{\"cm:title\":\"New Test title123\",\"hr:emp_no\":\"123456\",\"hr:lname\":\"Last_Name1\",\"hr:fname\":\"First_Name1\"}}";

我收到以下异常:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : [{"error":{"errorKey":"Could not read content from HTTP request body: Unrecognized field \"filedata\" (class org.alfresco.rest.api.model.Node), not marked as ignorable (36 known properties: "modifiedB... (1969 bytes)]

我在这里做错了什么或者漏掉了什么?

英文:

I am trying to upload a file to the DocLibrary folder using the below method:

private static void postTheDocument() {
		final String restENDPoint = &quot;http://servername:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/48eea6b2-fe9b-4cd2-8270-5caa35d7e8dc/children&quot;;
		RestTemplate restTemplate = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
		headers.setBasicAuth(&quot;admin&quot;, &quot;admin&quot;);
		String requestJson = &quot;{\&quot;name\&quot;: \&quot;TestName123s.doc\&quot;,\&quot;nodeType\&quot;: \&quot;hr:HR_Type\&quot;,\&quot;properties\&quot;:{\&quot;cm:title\&quot;:\&quot;New Test title123\&quot;,\&quot;hr:emp_no\&quot;:\&quot;123456\&quot;,\&quot;hr:lname\&quot;:\&quot;Last_Name1\&quot;,\&quot;hr:fname\&quot;:\&quot;First_Name1\&quot;}}&quot;;
		HttpEntity&lt;String&gt; entity = new HttpEntity&lt;String&gt;(requestJson, headers);
		HttpEntity&lt;String&gt; response = restTemplate.exchange(restENDPoint, HttpMethod.POST, entity,
				String.class);
		System.out.println(response.getBody().toString());
	}

The documentation suggest this:

curl -utest:test -X POST host:port/alfresco/api/-default-/public/alfresco/versions/1/nodes/12341234-2344-2344-43243242334/children -F filedata=@test.txt

Using the method postTheDocument() creates the empty document. But when I try below request:

String requestJson = &quot;{\&quot;filedata\&quot;: \&quot;@Z:/05test/YYYYest11qq890.pdf\&quot;,\&quot;name\&quot;: \&quot;TestName123s.doc\&quot;,\&quot;nodeType\&quot;: \&quot;hr:HR_Type\&quot;,\&quot;properties\&quot;:{\&quot;cm:title\&quot;:\&quot;New Test title123\&quot;,\&quot;hr:emp_no\&quot;:\&quot;123456\&quot;,\&quot;hr:lname\&quot;:\&quot;Last_Name1\&quot;,\&quot;hr:fname\&quot;:\&quot;First_Name1\&quot;}}&quot;;

I get the following Exception:

 Exception in thread &quot;main&quot; org.springframework.web.client.HttpClientErrorException$BadRequest: 400 : [{&quot;error&quot;:{&quot;errorKey&quot;:&quot;Could not read content from HTTP request body: Unrecognized field \&quot;filedata\&quot; (class org.alfresco.rest.api.model.Node), not marked as ignorable (36 known properties: \&quot;modifiedB... (1969 bytes)]

What I am doing wrong here or what I am missing?

答案1

得分: 1

我相信常见的方法是在Alfresco中创建节点,然后通过多部分上传将文件发送到节点,URL为"http://localhost:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children"(有关多部分上传的示例,请参见:https://www.baeldung.com/httpclient-multipart-upload)。

要从创建的节点获取节点ID:

    if (response != null) {
		try {
            JSONObject result;
			result = new JSONObject(response.getBody());
			System.out.println(result.toString());
              
            JSONObject oj = result.getJSONObject("entry");
            String id = (String) oj.get("id");

            System.out.println(id);
            fileupload(file_upload,id);

		} catch (JSONException e2) {
			e2.printStackTrace();
		}

    }
英文:

I believe the common approach is to create the node in Alfresco, then send the file to the node in a multipart upload to "http://localhost:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children" (for an example of multipart upload see: https://www.baeldung.com/httpclient-multipart-upload).

To get the node id from the created node:

    if (response != null) {
		try {
            JSONObject result;
			result = new JSONObject(response.getBody());
			System.out.println(result.toString());
              
            JSONObject oj = result.getJSONObject(&quot;entry&quot;);
            String id = (String) oj.get(&quot;id&quot;);

            System.out.println(id);
            fileupload(file_upload,id);

		} catch (JSONException e2) {
			e2.printStackTrace();
		}

    }        

答案2

得分: 1

发布适用于我的解决方案。虽然它不是基于RestTemplate的,但它有效。这是我从Alfresco支持团队那里获得的解决方案,它非常有效(请参阅内联注释):

private static void postFileAndMetadataToAlfresco() throws IOException, AuthenticationException {

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://someservername:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/12341234-1234-1234-1234-123412341234/children");
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials ("admin","adminpswd");
    httpPost.addHeader (new BasicScheme().authenticate(creds,httpPost, null));

    File payload = new File ("/path/to/my/file.pdf");

    MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 实体构建器

    builder.addPart("filedata", new FileBody(payload)); // 这是我遇到问题的地方
    builder.addTextBody ("name", "thenamegoeshere");
    builder.addTextBody ("foo", "foo");
    builder.addTextBody ("bar", "bar");
    builder.addTextBody ("description", "descriptiongoeshere");

    builder.addTextBody ("overwrite", "true");

    HttpEntity entity = builder.build();

    httpPost.setHeader("Accept","application/json");
    httpPost.setEntity(entity);

    CloseableHttpResponse response = httpClient.execute(httpPost); // 发送请求并获取响应

    System.out.println(response.toString()); // 将响应打印到控制台

    httpClient.close();  // 关闭客户端
}
英文:

Posting the solution that worked for me. Its not RestTemplate based but it works. This is the solution I got from Alfresco Support folks and it works perfectly well (refer the inline comments):

private static void postFileAndMetadataToAlfresco() throws IOException, AuthenticationException {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(&quot;http://someservername:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/12341234-1234-1234-1234-123412341234/children&quot;);
		UsernamePasswordCredentials creds = new UsernamePasswordCredentials (&quot;admin&quot;,&quot;adminpswd&quot;);
		httpPost.addHeader (new BasicScheme().authenticate(creds,httpPost, null));

		File payload = new File (&quot;/path/to/my/file.pdf&quot;);

		MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // Entity builder

		builder.addPart(&quot;filedata&quot;, new FileBody(payload)); // this is where I was struggling
		builder.addTextBody (&quot;name&quot;, &quot;thenamegoeshere&quot;);
		builder.addTextBody (&quot;foo&quot;, &quot;foo&quot;);
		builder.addTextBody (&quot;bar&quot;, &quot;bar&quot;);
		builder.addTextBody (&quot;description&quot;, &quot;descriptiongoeshere&quot;);

		builder.addTextBody (&quot;overwrite&quot;, &quot;true&quot;);

		HttpEntity entity = builder.build();

		httpPost.setHeader(&quot;Accept&quot;,&quot;application/json&quot;);
		httpPost.setEntity(entity);

		CloseableHttpResponse response = httpClient.execute(httpPost); // Post the request and get response

		System.out.println(response.toString()); // Response print to console

		httpClient.close();  // close the client
}

huangapple
  • 本文由 发表于 2020年10月3日 02:30:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64176613.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定