使用xutils向服务器提交文件(Android客户端代码)
xutils下载地址
下载之后,找到根目录下的xutils-2.4.14.jar的文件,如图
将jar导入到lib目录下:
eclipse可直接复制粘贴到lib目录下,Android studio用户和Intellij IDEA导入方法:连接
String sdpath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
Log.e("路径", String.valueOf(sdpath));
HttpUtils http = new HttpUtils();
RequestParams params = new RequestParams();
//附加用户名和密码
params.addQueryStringParameter("username", "wall");
params.addQueryStringParameter("password", "123");
//添加传送的文件路径和文件名
params.addBodyParameter("file", new File(sdpath + "/你要传送的文件"));
http.send(HttpMethod.POST, "http://172.168.9.26:8080/Mydemo/servlet/GetMyData",
params,
new RequestCallBack<String>() {
@Override
public void onFailure(HttpException arg0,
String arg1) {
// TODO Auto-generated method stub
Log.e("成功", String.valueOf(arg0));
}
@Override
public void onSuccess(ResponseInfo<String> arg0) {
// TODO Auto-generated method stub
Log.e("post成功", arg0.result);
}
});
服务器端使用jspSmartUpload接收文件:
jspSmartUpload获取地址
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username"); // 采用的编码是: iso-8859-1
String password = request.getParameter("password");
// 采用iso8859-1的编码对姓名进行逆转, 转换成字节数组, 再使用utf-8编码对数据进行转换, 字符串
username = new String(username.getBytes("iso8859-1"), "utf-8");
password = new String(password.getBytes("iso8859-1"), "utf-8");
File file = new File(GetMyData.class.getName());
System.out.println(file.getAbsolutePath());
System.out.println("姓名: " + username);
System.out.println("密码: " + password);
response.getOutputStream().write("提交成功".getBytes("utf-8"));
SmartUpload smartUpload = new SmartUpload();
try {
smartUpload.initialize(this.getServletConfig(), request, response);
smartUpload.upload();
com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0);
if (!smartFile.isMissing()) {
//设置接收文件之后的存储路径
String saveFileName = "E:\\apache-tomcat-7.0.62\\sevletGetImage\\" + smartFile.getFileName();
smartFile.saveAs(saveFileName, smartUpload.SAVE_PHYSICAL);
System.out.println("ok:" + saveFileName );
} else {
System.out.println("Missing....");
}
} catch (Exception e) {
System.out.println(e);
}
}
注意:在不指定接收文件的存储路径时,客户端也会显示提交成功,但是我至今不知道文件存储的位置,也可能是存储到内存之中。