您的位置:首页 > 理论基础 > 计算机网络

Httpurlconnection多文件上传问题。

2016-08-17 11:39 309 查看
public static void newloadMulti(final List<LocalImageUtils.LocalFile> files, final String RequestURL, final Handler handler, final int msgwhat, final int postion, final String dir) {

final String BOUNDARY = UUID.randomUUID().toString();  //边界标识   随机生成
final String PREFIX = "--", LINE_END = "\r\n";
final String CONTENT_TYPE = "multipart/form-data";   //内容类型

new Thread() {
@Override
public void run() {
super.run();

//                    File file = new File(files.get(i).getPath());
URL url = null;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String result = null;
//                    if (file != null && file.exists()) {
/**
* 当文件不为空,把文件包装并且上传
*/
try {
url = new URL(RequestURL);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(NEW_TIME_OUT);
conn.setConnectTimeout(NEW_TIME_OUT);
conn.setDoInput(true);  //允许输入流
conn.setDoOutput(true); //允许输出流
conn.setUseCaches(false);  //不允许使用缓存
conn.setRequestMethod("POST");  //请求方式
conn.setRequestProperty("Charset", CHARSET);  //设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
conn.addRequestProperty("dir", dir);
conn.addRequestProperty(Constant.Device, Constant.Device_Android);
conn.addRequestProperty(Constant.AppName, Constant.AppName_DBN);

dos = new DataOutputStream(conn.getOutputStream());

/**
* 这里重点注意:
* name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的   比如:abc.png
*/

for (int i = 0; i < files.size(); i++) {
LocalImageUtils.LocalFile localFile=files.get(i);
if(localFile.getPath()!=null&&!localFile.getPath().equals("")){
File upload=new File(localFile.getPath());
if(upload.exists()){
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"img"+i+"\"; filename=\"" + upload.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(upload);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
dos.write(LINE_END.getBytes());
is.close();
}
}
}

byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码  200=成功
* 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
if (res == 200) {
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
input.close();
result = sb1.toString();
} else {
result = Failed;
}
} catch (MalformedURLException e) {
e.printStackTrace();
result=Error;
} catch (IOException e) {
e.printStackTrace();
result=Error;
} finally {
if (result != null) {
NewUpdate updata;
if(result.equals(Error)){
updata=new NewUpdate();
updata.setError(2);
}else if(result.equals(Failed)){
updata=new NewUpdate();
updata.setError(1);
}else{
updata=JSON.parseObject(result,NewUpdate.class);
}
Message msg=Message.obtain();
msg.what=msgwhat;
msg.obj=updata;
handler.sendMessage(msg);
//                                UpdataResult updata;
//
//                                if (result.equals(Error)) {
//                                    updata = new UpdataResult();
//                                    updata.setPostion(postion + i);
//                                    updata.setError(1);
//
//                                } else if (result.equals(Failed)) {
//                                    updata = new UpdataResult();
//                                    updata.setPostion(postion + i);
//                                    updata.setError(2);
//                                } else {
//                                    updata = JSON.parseObject(result, UpdataResult.class);
//                                    updata.setPostion(postion + i);
//                                }
//                                updata.setFilename(files.get(i).getPath());
//                                Message msg = Message.obtain();
//                                msg.what = Constant.UpdataPhoto;
//                                msg.obj = updata;
//                                handler.sendMessage(msg);
}
try {
if (dos != null) {
dos.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//                    }

handler.sendEmptyMessage(Constant.Updata_Ok);

}
}.start();

}
先粘贴代码
出现问题:上传完成后后台只返回了一个url
问题原因:上传格式不正确。
解决方法:要注意filename 和name的设置 以及格式,大概流程是分割线标志开始,加入内容以及上传文件的流,之后end表示结束,
再设置第二个文件的内容以及文件上传的流,写入end结束。循环完毕之后在写入end,并且dos流flush。代表上传完毕。
另外:超时问题read是刷数据流中间断流了,然后超时,connect是前面连接过程超时。

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息