java - Android 将图像从 Drawable 上传到服务器
问题描述
嘿,我正在制作这个应用程序,用户在其中添加图像附件,然后将其发送到服务器。但是附件不是强制性的,所以用户仍然可以在不添加附件的情况下将其发送到服务器。如果用户不添加附件,它将发送默认图像。我想从drawable发送一个图像作为默认图像。我已经做了代码,但它不起作用。我的代码如下:
Resources resources = this.getResources();
Uri otherPath = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(R.drawable.image) + '/' + resources.getResourceEntryName(R.drawable.eimage));
String path = otherPath .toString();
imageFile.setImageBitmap(BitmapFactory.decodeFile(path));
File file1 = new File(path);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file1);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file1.getName(), requestBody);
它给了我错误:“打开失败:ENOENT(没有这样的文件或目录)。你有什么想法让这个工作吗?对不起我的英语不好。
解决方案
这里 id 是您的可绘制资源的标识符。示例:R.drawable.profile_image
现在使用这个输入流你可以创建一个文件
try
{
File f=new File("your file name");
InputStream inputStream = getResources().openRawResource(id);
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}
catch (IOException e){
}