我试图从服务器读取图像文件,代码如下。它一直在进入例外状态。我知道正确的字节数正在发送,因为我收到时将它们打印出来。我从蟒蛇发送图像文件像这样Android,读取二进制数据并将其写入文件
#open the image file and read it into an object
imgfile = open (marked_image, 'rb')
obj = imgfile.read()
#get the no of bytes in the image and convert it to a string
bytes = str(len(obj))
#send the number of bytes
self.conn.send(bytes + '\n')
if self.conn.sendall(obj) == None:
imgfile.flush()
imgfile.close()
print 'Image Sent'
else:
print 'Error'
这是Android的一部分,这是我遇到问题。关于接收图像并将其写入文件的最佳方式的任何建议?
//read the number of bytes in the image
String noOfBytes = in.readLine();
Toast.makeText(this, noOfBytes, 5).show();
byte bytes [] = new byte [Integer.parseInt(noOfBytes)];
//create a file to store the retrieved image
File photo = new File(Environment.getExternalStorageDirectory(), "PostKey.jpg");
DataInputStream dis = new DataInputStream(link.getInputStream());
try{
os =new FileOutputStream(photo);
byte buf[]=new byte[1024];
int len;
while((len=dis.read(buf))>0)
os.write(buf,0,len);
Toast.makeText(this, "File recieved", 5).show();
os.close();
dis.close();
}catch(IOException e){
Toast.makeText(this, "An IO Error Occured", 5).show();
}
编辑:我仍然不能得到它的工作。从那以后,我一直在这样做,而我所有努力的结果要么导致文件不是全尺寸,要么导致应用程序崩溃。发送服务器端之前我知道文件没有损坏。据我可以告诉它肯定也发送,因为发送所有方法在python发送全部或抛出一个异常的情况下发生的错误,迄今为止,它从来没有抛出异常。所以客户端很混乱。我必须从服务器发送文件,所以我不能使用Brian建议的建议。
你有没有得到任何数据?你得到的任何错误? – dongshengcn 2011-02-17 17:35:07
是的,我得到的字节数,但没有图像数据。服务器说图像已发送,客户端捕获io异常并显示发生了IO错误。 – Shpongle 2011-02-17 17:39:09