核心代码: 1、布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/et_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入要上传的文件的路径"
android:text="http://192.168.221.221:8080/FileUpload/FileUploadServlet"
android:inputType="textUri" >
<requestFocus />
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="上传"
android:onClick="upload"
/>
</LinearLayout> 2、MainActivity.java
import java.io.File;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class MainActivity extends Activity {
private EditText et_path;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) this.findViewById(R.id.et_path);
}
/**
* 文件上传
*/
public void upload(View v) {
String path = et_path.getText().toString();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this.getApplicationContext(), "路径不能为空!", 0).show();
}
try {
File file = new File(Environment.getExternalStorageDirectory(),"backup.xml");
if (!file.exists()) {
Toast.makeText(this.getApplicationContext(), "文件不存在", 0).show();
return;
}
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("file", file);
asyncHttpClient.post(path, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String content) {
Toast.makeText(getApplicationContext(), content, 0).show();
}
@Override
public void onFailure(Throwable error, String content) {
Toast.makeText(getApplicationContext(), "上传文件失败。。。", 0).show();
error.printStackTrace();
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} 3、FileUploadServlet .java
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = -8336588521811908689L;
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException {
response.setCharacterEncoding("utf-8");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);//表单是否有属性enctype="multipart/form-data"
if (isMultipart) { // 如果有,说明是个文件上传的表单
String realpath = request.getSession().getServletContext().getRealPath("/files");
System.out.println(realpath);
File dir = new File(realpath);
if(!dir.exists()) dir.mkdirs();
// 1、获取文件上传工厂
FileItemFactory factory = new DiskFileItemFactory();
// 2、
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
List<FileItem> items = upload.parseRequest(request);//3、获取每一个item项
for(FileItem item : items){
if (item.isFormField()) { // 3-1为普通的item
String name1 = item.getFieldName();//得到请求参数的名称
String value = item.getString("UTF-8");//得到参数值
System.out.println(name1+ "="+ value);
} else { // 3-2为文件上传item项
System.out.println(item.getName());
item.write(new File(dir, System.currentTimeMillis()+"_"+ item.getName() ));
response.getWriter().write("文件上传成功");
}
}
} catch (Exception e) {
e.printStackTrace();
response.getWriter().write("文件上传失败");
}
}else{
doGet(request, response);
}
}
} |