一.概述

文件上传是项目中经常用到的功能,今天给大家介绍二个文件上传的工具类,利用的是HttpURLConnection,并且都是亲测可用的哦,有问题可以直接找我。

二.代码

1.UploadUtil.java

public class UploadUtil {
public static final String ENCORDING = "utf-8";
/**
* 文件上传
* @param filepath 文件完整路径,包括文件名
* @param serverUrl 上传的服务器地址
* @return
*/
public static boolean upload(String filepath,String serverUrl) {
//起始标记分隔线
String boundary = "---------------------------7db1c523809b2";//+java.util.UUID.randomUUID().toString();//
//将完整路径封装成文件
File file = new File(filepath);
//从完整路径中获取文件名称
String name = filepath.substring(filepath.lastIndexOf("/")+1);
String fileName = null;
try {
fileName = new String(name.getBytes(), "ISO-8859-1");
//拼接url
URL url = new URL(serverUrl + "?filename=" + fileName + "&filetype=IMAGE");
// 用来拼接请求
StringBuilder sb = new StringBuilder();
/*// username字段
sb.append("--" + boundary + "\r\n");
sb.append("Content-Disposition: form-data; name=\"username\"" + "\r\n");
sb.append("\r\n");
sb.append(username + "\r\n");

// password字段
sb.append("--" + boundary + "\r\n");
sb.append("Content-Disposition: form-data; name=\"password\"" + "\r\n");
sb.append("\r\n");
sb.append(password + "\r\n");*/

// 文件部分
sb.append("--" + boundary + "\r\n");
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + filepath + "\"" + "\r\n");
//此Content-Type代表二进制流,不知道下载文件类型
sb.append("Content-Type: application/octet-stream" + "\r\n");
sb.append("\r\n");

// 将开头和结尾部分转为字节数组,因为设置Content-Type时长度是字节长度
byte[] before = sb.toString().getBytes(ENCORDING);
byte[] after = ("\r\n--" + boundary + "--\r\n").getBytes(ENCORDING);

// 打开连接, 设置请求头
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setRequestProperty("Content-Length", before.length + file.length() + after.length + "");

conn.setDoOutput(true);//允许输出流
conn.setDoInput(true);//允许输出流

// 获取输入输出流
OutputStream out = conn.getOutputStream();
FileInputStream fis = new FileInputStream(file);
// 将开头部分写出
out.write(before);

// 写出文件数据
byte[] buf = new byte[1024 * 5];
int len;
while ((len = fis.read(buf)) != -1)
out.write(buf, 0, len);

// 将结尾部分写出
out.write(after);
//获取服务器过来的输入流
InputStream in = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(isReader);
String line = null;
String data = "getResult=";
while ((line = bufReader.readLine()) != null)
data += line;
Log.e("fromServer", "result=" + data);
boolean sucess = conn.getResponseCode() == 200;
in.close();
fis.close();
out.close();
conn.disconnect();
return sucess;
} catch (Exception e1) {
e1.printStackTrace();
}
return false;
}
}

2.UploadUtil.java

public class Upload {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10*1000; //超时时间
private static final String CHARSET = "utf-8"; //设置编码
/**
* android上传文件到服务器
* @param file 需要上传的文件
* @param RequestURL 请求的rul
* @return 返回响应的内容
*/
public static String uploadFile(File file, String RequestURL)
{
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
String PREFIX = "--" , LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; //内容类型
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(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);
if(file!=null)
{
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);//起始标记
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意:
* name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.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(file);
byte[] bytes = new byte[1024];
int len = 0;
while((len=is.read(bytes))!=-1)
{
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
//结束标志符号
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) {
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();//获取服务器的响应流
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + result);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}