首页 > 代码库 > 关于文件上传下载
关于文件上传下载
之前测服务端上传下载的Demo 测试通过 能进行上传下载 有兴趣的可以优化优化代码
public static boolean uploadFile(File file, String url) {
String CHARSET = "utf-8";
boolean upload = false;
FileInputStream fis = null;
URL mUrl = null;
HttpURLConnection conn = null;
String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型
try {
mUrl = new URL(url);
conn = (HttpURLConnection) mUrl.openConnection();
conn.setReadTimeout(5000); //
conn.setConnectTimeout(5000);
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=\"file\"; 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; int send=0;
while ((len = is.read(bytes)) != -1) {
// System.out.println("len: " + len);
dos.write(bytes, 0, len);
send+=len; dos.flush();
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = http://www.mamicode.com/(PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data); dos.flush();
/** * 获取响应码 200=成功 当响应成功,获取响应的流 */
int res = conn.getResponseCode();
if (res == 200) {
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
upload = true;
}
}
} catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return upload; }
关于文件上传下载