很多时候在做项目中会有上传文件的需求,那么我们就聊聊这个代码怎么写,废话不多直接上代码。
客户端代码:
public class MainActivity extends Activity {
private EditText etPath;
private ProgressBar pb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etPath = (EditText) findViewById(R.id.et_path);
pb = (ProgressBar) findViewById(R.id.pb);
}
/**
* 点击按钮
*
* @param view
*/
public void upload(View view) {
String path = etPath.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "请输入文件的位置", 0).show();
return;
}
String urlPath = "http://192.168.1.253:8080/web/UploadServlet";
// 1. 初始化客户端
AsyncHttpClient client = new AsyncHttpClient();
// 上传的文件
File file = new File(path);
if (file.exists()) {
RequestParams params = new RequestParams();
try {
params.put("file", file);
} catch (Exception e) {
e.printStackTrace();
}
// 2. post提交文件
client.post(urlPath, params, new AsyncHttpResponseHandler() {
// 上传文件成功
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
Toast.makeText(MainActivity.this, new String(responseBody),
0).show();
}
/**
* 上传的进度
*/
@Override
public void onProgress(int bytesWritten, int totalSize) {
super.onProgress(bytesWritten, totalSize);
// 设置总进度
pb.setMax(totalSize);
// 上传的进度
pb.setProgress(bytesWritten);
}
// 上传文件失败
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, new String(responseBody),
0).show();
}
});
}
}
}
web端代码:
public class UploadServlet extends HttpServlet {private static final long serialVersionUID = 1L;/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {// 判断上传的是否包含文件boolean isMultipart = ServletFileUpload.isMultipartContent(request);if (isMultipart) {// 获取路径String realpath = request.getSession().getServletContext().getRealPath("/files");System.out.println(realpath);File dir = new File(realpath);if (!dir.exists())dir.mkdirs();FileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8");try {// 解析请求参数 其实就是 form表单的每个input节点List items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// 如果是表单 解析每个表单 打印到控制台
String name1 = item.getFieldName();// 得到请求参数的名称
String value = item.getString("UTF-8");// 得到参数值
System.out.println(name1 + "=" + value);
} else {
// 把文件写到当前servlet所对应的路径
item.write(new File(dir, System.currentTimeMillis()
+ item.getName().substring(
item.getName().lastIndexOf("."))));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
就这么简单,可以上传、接收任何文件,框架是以流的方式传输的, 特别大的文件 可能会卡。