android httpurlconnection 上传图片,通过HttpUrlConnection实现文件上传

帮助文档

the user enters "Larry" in the text input, and selects the text file "file1.txt", the user agent might send back the following data:Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x

Content-Disposition: form-data; name="submit-name"

Larry

--AaB03x

Content-Disposition: form-data; name="files"; filename="file1.txt"

Content-Type: text/plain

... contents of file1.txt ...

--AaB03x--

注意:网上编写的代码可能编译环境的不同,代码的表示也是不同的,再或者本身没有实现,一定找到规定书写的帮助文档,直接对照书写代码。

具体的代码实现:

String urlStr = " ";

URL url = new URL(urlStr);

HttpURLConnection http = (HttpURLConnection) url.openConnection();

http.setRequestMethod("POST");

//上传文件形式 "multipart/form-data"

http.setRequestProperty("Content-Type", "multipart/form-data; boundary=----footfoodapplicationrequestnetwork");

//boundary自定义的分隔符的类型

http.setRequestProperty(

"Accept",

"image/gif,   image/x-xbitmap,   image/jpg,   image/pjpeg,   application/vnd.ms-excel,   application/vnd.ms-powerpoint,                                  application/msword,   application/x-shockwave-flash,   application/x-quickviewplus,   */*");

http.setDoOutput(true);

http.setDoInput(true);

//若提交为post方式,需要修改为false

http.setUseCaches(false);

System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒

System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒

http.connect();

fin = new FileInputStream(filepath);

byte[] bytes = new byte[1024];

BufferedOutStream os = null;

//输入数据

os = new BufferedOutputStream(http.getOutputStream());

//注意格式  --boundary

//name="files"  (文件类型)filename="pic_1.jpg" (有很多地方是说是根路径,其实不是就是单纯的文件名)

buffer.append("------footfoodapplicationrequestnetwork\r\n");

buffer.append("Content-Disposition:form-data;name=\"files\";" );

buffer.append("filename=\"");

buffer.append("pic_1.jpg"+"\"");

buffer.append("\r\n");

buffer.append("Content-Type: image/jpg");   //如果是图片,或者音频,文本文件类型的那么还需要隔一行进行添加内容

buffer.append("\r\n\r\n");

os.write(buffer.toString().getBytes());

int bytelength;

while((bytelength=fin.read(bytes))!=-1){

os.write(bytes, 0, bytelength);

}

//文件传输结束格式:--boundary--

os.write("\r\n------footfoodapplicationrequestnetwork--\r\n".getBytes());

//接收网络返回内容

ins = http.getInputStream();

int size = ins.available();

byte[] jsonBytes = new byte[size];

ins.read(jsonBytes);

String message = new String(jsonBytes, "utf-8");

JSONObject demoJson = new JSONObject(message);

String media_id = demoJson.getString("media_id");

if(media_id!=null){

System.out.println(media_id);

return "图片上传成功!";

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Android应用中将文件上传到服务器,可以按照以下步骤进行操作: 1. 首先,确保应用的AndroidManifest.xml文件中添加了以下权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> ``` 这样才能进行网络通信。 2. 创建一个HTTP请求来上传文件。可以使用Java的HttpURLConnection类或者第三方库如OkHttp或Volley来实现。以下是使用HttpURLConnection的示例代码: ```java URL url = new URL("http://example.com/upload"); // 服务器的上传地址 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); // 设置请求头 connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); // 创建请求体 DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes("--" + boundary + "\r\n"); outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + "\r\n"); outputStream.writeBytes("Content-Type: " + mimeType + "\r\n\r\n"); // 将文件数据写入请求体 File file = new File(filePath); FileInputStream fileInputStream = new FileInputStream(file); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileInputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.writeBytes("\r\n"); outputStream.writeBytes("--" + boundary + "--\r\n"); // 关闭流 fileInputStream.close(); outputStream.flush(); outputStream.close(); // 获取服务器响应 int responseCode = connection.getResponseCode(); ``` 在上面的代码中,你需要修改以下变量: - `url`:服务器的上传地址。 - `boundary`:用于分隔请求体中不同部分的边界字符串。 - `fileName`:要上传的文件名。 - `mimeType`:文件的MIME类型。 - `filePath`:要上传的文件的本地路径。 3. 处理服务器的响应。可以根据`responseCode`来判断上传是否成功,以及根据需要处理服务器返回的数据。 请注意,上述代码仅为示例,实际实现中可能需要根据你的服务器端要求进行一些调整。另外,为了更好的用户体验,可以将文件上传操作放在后台线程中执行,以避免阻塞主线程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值