Android端上传文件到Web服务器
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Android端上传文件到Web服务器,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含5985字,纯文字阅读大概需要9分钟。
内容图文
本文中主要就Android端上传文件到Web服务器,做出的一个简单的Demo
1、Tomcat上部署的服务端的实现
2、Android端的代码实现
1、Tomcat服务器上面项目的部署与实现
创建一个Web Project
创建FileUploadServlet.java,当然,一下两个重要的Jar包不能够忘记!
commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
FileUploadServlet.java
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
publicclassFileUpLoadServletextendsHttpServlet {privatestaticfinallong serialVersionUID = 1L;
publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
publicvoiddoPost(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 {
@SuppressWarnings("unchecked")
List<FileItem> 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 {
item.write(new File(dir, System.currentTimeMillis()
+ item.getName().substring(
item.getName().lastIndexOf("."))));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Web.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-appversion="2.5"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>
</display-name>
<servlet>
<servlet-name>FileUpLoadServlet</servlet-name><servlet-class>com.fileupload.FileUpLoadServlet</servlet-class></servlet><servlet-mapping><servlet-name>FileUpLoadServlet</servlet-name><url-pattern>/FileUpLoadServlet</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>
2、Android端的代码实现
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.fileuploadtoserver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et_uploadpath"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入上传的文件路径" />
<Button
android:onClick="upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="上传文件"/>
</LinearLayout>
导入开源项目:com.loopj.android.http;可以再Github上下载
Git地址:https://github.com/loopj/android-async-http
MainActivity.java
import java.io.File;
import java.io.FileNotFoundException;
import org.apache.http.Header;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
publicclassMainActivityextendsActivity {private EditText et_path;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) this.findViewById(R.id.et_uploadpath);
}
publicvoidupload(View view) throws FileNotFoundException {
String path = et_path.getText().toString().trim();
String server_upload_path = "http://192.168.3.36:8080/AndroidWebServerDemo1/FileUpLoadServlet";
File file = new File(path);
if(file.exists() && file.length() > 0) {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("tempfile", file);
client.post(server_upload_path, params, new AsyncHttpResponseHandler() {
@OverridepublicvoidonSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Toast.makeText(getApplicationContext(), "上传成功", 0).show();
}
@OverridepublicvoidonFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(getApplicationContext(), "上传失败", 0).show();
}
});
} else {
Toast.makeText(getApplicationContext(), "无效路径", 0).show();
}
}
}
原文:http://blog.csdn.net/yangqian201175/article/details/51338029
内容总结
以上是互联网集市为您收集整理的Android端上传文件到Web服务器全部内容,希望文章能够帮你解决Android端上传文件到Web服务器所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。