如何在Android中恢复文件上传过程?
我正在使用此代码在服务器上上载文件,但我需要这样的功能:如果在上载过程中由于网络丢失或任何其他中断而停止,则不应该从第二次开始上载。来自服务器的响应也是可定制的。在安卓系统中可能吗?我应该用什么方法来做这件事?请引导我。 如果可能的话,请向我推荐任何代码示例 谢谢如何在Android中恢复文件上传过程?,android,network-programming,Android,Network Programming,我正在使用此代码在服务器上上载文件,但我需要这样的功能:如果在上载过程中由于网络丢失或任何其他中断而停止,则不应该从第二次开始上载。来自服务器的响应也是可定制的。在安卓系统中可能吗?我应该用什么方法来做这件事?请引导我。 如果可能的话,请向我推荐任何代码示例 谢谢 public String uploadFile(InputStream is) { HttpURLConnection conn; String jsonResponse = ""; int streamSi
public String uploadFile(InputStream is) {
HttpURLConnection conn;
String jsonResponse = "";
int streamSize = 0;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesAvailable, bufferSize;
byte[] buffer;
String urlString = "*******<My URL>*******";
try {
// ------------------ CLIENT REQUEST
// FileInputStream fileInputStream = new FileInputStream(new
// File(selectedPath) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
conn.setChunkedStreamingMode(0);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"wheeze_file\";filename="
+ fileName + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = is.available();
streamSize = bytesAvailable;
bufferSize = 2048;
buffer = new byte[bufferSize];
// read file and write it into form...
int i = 0;
int length = 0;
while ((length = is.read(buffer, 0, bufferSize)) > 0) {
if (isCancelled()) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
return null;
}
dos.write(buffer, 0, length);
bytesAvailable = is.available();
// bufferSize = Math.min(bytesAvailable, maxBufferSize);
publishProgress(streamSize, bytesAvailable);
// Log.v("Progress",""+streamSize+" : "+bytesAvailable);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"data[authentication][email]\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(username);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"data[authentication][password]\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(enc_password);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"method\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes("uploadWheezeFile");
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
// Log.v("Conn status", "Disconnected");
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Debug", "MURLExerror: " + ex.getMessage(), ex);
} catch (IOException ioe) {
ioe.printStackTrace();
Log.e("Debug", "IOEx error: " + ioe.getMessage(), ioe);
uploadTask.cancel(true);
return null;
} finally {
try {
is.close();
dos.flush();
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// ------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream(conn.getInputStream());
if ((jsonResponse = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + jsonResponse);
} else {
jsonResponse = "";
}
inStream.close();
conn.disconnect();
//
} catch (IOException ioex) {
ioex.printStackTrace();
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
return jsonResponse;
}
公共字符串上载文件(InputStream为){
httpurl连接连接;
字符串jsonResponse=“”;
int streamSize=0;
DataOutputStream dos=null;
DataInputStream inStream=null;
字符串lineEnd=“\r\n”;
字符串双连字符=“--”;
字符串边界=“*******”;
int字节可用,缓冲区大小;
字节[]缓冲区;
字符串urlString=“*************”;
试一试{
//--------------客户端请求
//FileInputStream FileInputStream=newfileinputstream(new
//文件(selectedPath));
//打开到Servlet的URL连接
URL=新URL(URL字符串);
//打开到URL的HTTP连接
conn=(HttpURLConnection)url.openConnection();
//允许输入
conn.setDoInput(真);
//允许输出
连接设置输出(真);
//不要使用缓存副本。
conn.SETUSECHACHES(假);
conn.setChunkedStreamingMode(0);
//使用post方法。
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“内容类型”,
“多部分/表单数据;边界=”+边界);
dos=新的DataOutputStream(conn.getOutputStream());
写字节(两个连字符+边界+行结束);
writeBytes(“内容处置:表单数据;名称=\“wheeze\u文件\”文件名=”
+文件名+行尾);
dos.writeBytes(lineEnd);
//创建最大大小的缓冲区
bytesAvailable=is.available();
streamSize=字节可用;
缓冲区大小=2048;
buffer=新字节[bufferSize];
//读取文件并将其写入表单。。。
int i=0;
整数长度=0;
而((长度=is.read(缓冲区,0,缓冲区大小))>0){
如果(isCancelled()){
Toast.makeText(getApplicationContext(),“已取消”,
吐司。长度(短)。show();
返回null;
}
写入(缓冲区,0,长度);
bytesAvailable=is.available();
//bufferSize=Math.min(字节可用,maxBufferSize);
发布进度(流大小,字节数可用);
//Log.v(“进度”,“流大小+”:“+字节可用”);
}
//发送文件数据后所需的多部分表单数据。。。
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+行结束);
dos.writeBytes(“内容处置:表单数据;名称=\”数据[身份验证][电子邮件]\”
+线路端);
dos.writeBytes(lineEnd);
dos.writeBytes(用户名);
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+行结束);
dos.writeBytes(“内容处置:表单数据;名称=\”数据[身份验证][密码]\”
+线路端);
dos.writeBytes(lineEnd);
dos.writeBytes(加密密码);
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+行结束);
dos.writeBytes(“内容处置:表单数据;名称=\”方法“”
+线路端);
dos.writeBytes(lineEnd);
写字节(“上传文件”);
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+行结束);
写字节(两个连字符+边界+两个连字符+行结束);
//合流
Log.e(“调试”,“文件已写入”);
//日志v(“连接状态”、“断开”);
}捕获(格式错误){
例如printStackTrace();
Log.e(“Debug”,“MURLExerror:”+ex.getMessage(),ex);
}捕获(ioe异常ioe){
ioe.printStackTrace();
Log.e(“调试”,“IOEx错误:”+ioe.getMessage(),ioe);
上载任务。取消(true);
返回null;
}最后{
试一试{
is.close();
dos.flush();
dos.close();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
//--------------读取服务器响应
试一试{
inStream=新数据输入流(conn.getInputStream());
if((jsonResponse=inStream.readLine())!=null){
Log.e(“调试”、“服务器响应”+jsonResponse);
}否则{
jsonResponse=“”;
}
流内关闭();
连接断开();
//
}捕获(IOException ioex){
ioex.printStackTrace();
Log.e(“调试”,“错误:”+ioex.getMessage(),ioex);
}
返回jsonResponse;
}
如果接收服务器支持,您可以使用Content Range标头来标识正在恢复的上载。googledriveapi支持它。如果你自己动手,我会遵循谷歌使用的模式:
- 开始上传并获取会话标识符
- 上载被中断时,请等待互联网恢复
- 恢复上载时,首先询问服务器已接收多少字节。(*)
- 使用服务器状态后的下一个字节继续上载
(*)请注意,当我以前滚动自己的响应时,我添加了一个来自服务器的编码响应,其中包含最后KB的上载,只是为了验证它在传输过程中没有损坏。然而,在生产过程中,我从未见过服务器接收到损坏数据的情况。是否有任何方法可以确定接入点仍然连接到手机,但接入点丢失了互联网?是的,@Droider,谷歌it就是一个例子。它真的什么都没有