我正在使用Loopj将文件上传到我的WordPress站点和WP REST API v1和/或v2(相同的结果).
身份验证很棒,标题很棒,文件"上传"但是当我在我的WordPress后端检查它时...图像或文件被破坏了.
Android部分是这样的:
File myFile = new File(finalpath); String name = Utils.getLastBitFromUrl(finalpath); String extension = Utils.getFileExtention(finalpath); client.setBasicAuth("myusername", "mypassword", new AuthScope("mywebsite.com", 80, AuthScope.ANY_REALM)); client.addHeader("Content-Disposition", "filename=" + name); client.addHeader("Content-Type", "image/" + extension); try { params.put("data", myFile); } catch (FileNotFoundException e) { e.printStackTrace(); } // or: http://mywebsite.com/wp-json/wp/v2/media for v2 client.post("http://mywebsite.com/wp-json/media", params, new AsyncHttpResponseHandler() { int count = 0; @Override public void onStart() { prgDialog = new ProgressDialog(MainActivity.this); prgDialog.setMessage("Uploading Image..."); prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); prgDialog.setMax(100); prgDialog.show(); } @Override public void onProgress(long bytesWritten, long totalSize) { if(count < 1){ count++; Log.d("size", "" + Utils.formatFileSize(totalSize)); } long progressPercentage = (long)100*bytesWritten/totalSize; if(progressPercentage <= 100) { prgDialog.setProgress((int) progressPercentage); } } @Override public void onSuccess(int statuscode, Header[] headers, byte[] response) { try { prgDialog.dismiss(); JSONObject obj = new JSONObject(Utils.decodeUTF8(response)); Log.e("success!", Utils.decodeUTF8(response)); } catch (JSONException e) { e.printStackTrace(); }
但是图像......在我的WordPress后端看起来像这样:
有谁知道为什么会这样?我的文件和文件路径是完美的.在上传之前,我可以获取图像并将其显示在手机上.
编辑:这个cURL非常完美
curl -i -X POST -H "Content-Disposition:filename=test.png" --data-binary @"/home/my-name/Downloads/example.png" -d title="test" -u username:password -H "Expect:" http://my.website.com/wp-json/wp/v2/media
主要区别在于--data-binary @但我不知道如何在Java上做到这一点.