gpt4 book ai didi

安卓图片上传AWS服务器

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:57:16 27 4
gpt4 key购买 nike

使用以下代码在服务器上上传图片-

final InputStream fileInputStream = MyApplication.getInstance().getContentResolver().openInputStream(imageFile);
bitmap = BitmapFactory.decodeStream(fileInputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
final byte[] bitmapData = byteArrayOutputStream.toByteArray();

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

// Add binary body
if (bitmap != null) {
ContentType contentType = ContentType.create("image/png");
builder.addBinaryBody("", bitmapData, contentType, "");

final HttpEntity httpEntity = builder.build();
StringRequest request =
new StringRequest(Request.Method.PUT, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpEntity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
};

上传图片没问题,但在文件中添加了正文标题

--0Iw7PkPg_BhQghFGBR1_lBhO1RaCaBsZJ-U
Content-Disposition: form-data; name=""; filename=""
Content-Type: image/png
âPNG
....
--0Iw7PkPg_BhQghFGBR1_lBhO1RaCaBsZJ-U--

如果我从文件中删除该特定内容,则该图像可以轻松用作 PNG。有没有办法只上传PNG文件部分到服务器?

最佳答案

我在尝试将图像上传到 AWS 服务器时遇到了同样的问题。我已将其作为 octet-stream 发送。我使用过改造 2.2。 注意:如果我们使用 Octet-stream,则无需将其作为多部分请求。

@PUT
Observable<Response<Void>> uploadMedia(
@Header("Content-Type") String contentType, @Header("filetype")
String FileType,
@Url String urlPath, @Body RequestBody picture);


private void UploadSignedPicture(String url, File filename, String mediaUrl) {

mAmazonRestService.uploadMedia("application/octet-stream", "application/octet-stream", url, mAppUtils.requestBody(filename)).
subscribeOn(mNewThread).
observeOn(mMainThread).
subscribe(authenticateResponse -> {
if (this.isViewAttached()) {

if (authenticateResponse.code() == ApiConstants.SUCCESS_CODE)

else

}
}, throwable -> {
if (isViewAttached())
getMvpView().showServerError(this, throwable);
}
});
}

最重要的是如何创建请求:

@NonNull
public RequestBody requestBody(File filename) {

InputStream in = null;
byte[] buf = new byte[0];
try {
in = new FileInputStream(new File(filename.getPath()));
buf = new byte[in.available()];
while (in.read(buf) != -1) ;
} catch (IOException e) {
e.printStackTrace();
}
return RequestBody
.create(MediaType.parse("application/octet-stream"), buf);
}

谢谢,希望对你有帮助。

关于安卓图片上传AWS服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45531319/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com