Android文件上传到服务端实践指南
115 浏览量
更新于2024-09-01
收藏 74KB PDF 举报
Android 上传文件到服务端并显示进度条
Android 上传文件到服务端并显示进度条是 Android 开发中的一项重要技术,以下是该技术的详细知识点:
一、Android 上传文件到服务端
Android 上传文件到服务端主要使用的是 HttpURLConnection 类,该类提供了基本的 HTTP 连接功能,可以用来实现文件上传。下面是一个简单的示例代码:
```java
private class UploadTask extends AsyncTask<Object, Integer, Void> {
private DataOutputStream outputStream = null;
private String fileName;
private String uri;
private String mLineEnd = "\r\n";
private String mTwoHyphens = "--";
private String boundary = "*";
File uploadFile;
long mTtotalSize; // Getsize of file, bytes
public UploadTask(String fileName, String uri) {
this.fileName = fileName;
this.uri = uri;
uploadFile = new File(fileName);
mTtotalSize = uploadFile.length();
}
/
* 开始上传文件
*
* @param objects
* @return
*/
@Override
protected Void doInBackground(Object... objects) {
long length = 0;
int mBytesRead, mBytesAvailable, mBufferSize;
byte[] buffer;
int maxBufferSize = 256 * 1024; // 256KB
try {
FileInputStream fileInputStream = new FileInputStream(new File(fileName));
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = new DataOutputStream(con.getOutputStream());
// 上传文件
outputStream.writeBytes(mTwoHyphens + boundary + mLineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"" + mLineEnd);
outputStream.writeBytes(mLineEnd);
byte[] buffer = new byte[maxBufferSize];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer, 0, maxBufferSize)) != -1) {
outputStream.write(buffer, 0, bytesRead);
length += bytesRead;
publishProgress((int) ((length / (float) mTtotalSize) * 100));
}
outputStream.writeBytes(mLineEnd);
outputStream.writeBytes(mTwoHyphens + boundary + mTwoHyphens + mLineEnd);
int responseCode = con.getResponseCode();
if (responseCode == 200) {
Log.d("UploadTask", "上传成功");
} else {
Log.d("UploadTask", "上传失败");
}
} catch (Exception e) {
Log.d("UploadTask", "上传失败" + e.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
Log.d("UploadTask", "关闭流失败" + e.getMessage());
}
}
return null;
}
}
```
二、显示进度条
显示进度条可以使用 Android 提供的 ProgressBar 组件,以下是一个简单的示例代码:
```java
private ProgressBar mPgBar;
// 在AsyncTask中更新进度条
@Override
protected void onProgressUpdate(Integer... progress) {
mPgBar.setProgress(progress[0]);
}
// 在AsyncTask中显示进度条
@Override
protected void onPostExecute(Void result) {
mPgBar.setVisibility(View.GONE);
}
```
三、服务端代码
服务端代码可以使用多种语言实现,以下是一个使用 Java 实现的简单示例代码:
```java
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getHeader("file");
File file = new File("upload/" + fileName);
if (!file.exists()) {
file.mkdirs();
}
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
String name = item.getFieldName();
if (item.isFormField()) {
String value = item.getString();
System.out.println("Form field " + name + " with value " + value);
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
System.out.println("Field " + fieldName);
System.out.println("FileName " + fileName);
System.out.println("ContentType " + contentType);
System.out.println("Size (bytes) " + sizeInBytes);
System.out.println("InMemory " + isInMemory);
// 保存文件
File uploadedFile = new File("upload/" + fileName);
item.write(uploadedFile);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
Android 上传文件到服务端并显示进度条是一项复杂的技术,需要使用多种技术栈,包括 HttpURLConnection、AsyncTask、ProgressBar 等,但通过合理的设计和实现,我们可以实现该功能。
345 浏览量
213 浏览量
736 浏览量
108 浏览量
2021-12-29 上传
2014-09-23 上传
2020-10-13 上传
511 浏览量
207 浏览量
weixin_38731761
- 粉丝: 7
- 资源: 920
最新资源
- linux常用指令介绍
- 122道Java面试题大全(包含答案)-面试宝典
- Lotus Domino邮件服务器全攻略
- MCSE(网络架构操作题)
- AutoCAD 快捷键大全
- Oracle+Call+Interface+-+Programmer's+Guide
- ASP.NET专业项目实例开发(修订版)-课件(部分)
- ucos嵌入式实时操作系统(第二版).pdf
- WebSpherePortal6.1集群安装
- rails22cn.pdf
- vimbook详细学习手册
- ArcGIS二次开发编程实例
- Netcool Omnibus 知识集锦
- Sniffer Pro 入门指南 4.7版
- ARCGIS数字化教程
- AT89S52中文资料