android app 浅谈文件上传(图片和文件)
16lz
2021-01-23
说到图片上传,文件上传就让初学的我头疼。。。。今天就来浅谈一下用原生的代码实现的图片,以及文件的上传吧,看的不是很透彻,如有 不足之处,希望能得到您的回复赐教。还有到目前为止,初学者的我还没有找到好用的上传文件的框架或者第三方,如您有好用的框架,望不惜赐教。
直接上代码(代码上没什么难度就不注释了,直接拿来用就行了)
public static String uploadLvzhiFiles(ArrayList<File> files, String RequestURL) { int res = 0; 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 (files != null && files.size() > 0) { DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); for (File file : files) { System.out.println("fileName:" + file.getName()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); sb.append("Content-Disposition: form-data; name=\"file[]\"; filename=\"" + file.getName() + "\"" + LINE_END); System.out.println(file.getName() + "-------file.getName-------"); sb.append("Content-Type: application/octet-stream; charset=+CHARSET"+LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); System.out.println(file.length()); 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("\r\n\r\n".getBytes()); } byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END) .getBytes(); dos.write(end_data); dos.flush(); res = conn.getResponseCode(); System.out.println(res+"-------上传连接是否成功-------"); if (res == 200) { InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); } else { result = ""; } } } catch (MalformedURLException e) { e.printStackTrace(); System.out.println(e.getMessage().toString()+"--------catch (MalformedURLException e)------"); } catch (IOException e) { e.printStackTrace(); System.out.println(e.getMessage().toString()+"--------IOException e------"); } return result;}上传参数不同,修改file[ ] 即可
如果上传图片,一定要进行严格的压缩再上传,不然很容易报OOM。
原创文章,转载请注明出处: http://blog.csdn.net/qq_33078541?viewmode=contents
更多相关文章
- 怎样写一个类似ROS的易用的android机器人框架(2)
- Android OpenGL ES(六)----进入三维在代码中创建投影矩阵和旋转
- Android中使用开源框架EventBus3.0实现Fragment之间的通信交互
- 观摩Android的多层框架体系
- 框架模式MVP在Android中的使用
- SPDY协议的Android实现 OKHTTP代码分析
- 15款android设备上的代码编辑器
- Android 依赖注入(DI)框架 Dagger
- Android新姿势:截屏代码整理