android 上传文件到 c 服务器,android通过servlet上传文件到服务器

本文实例为大家分享了android通过servlet上传文件到服务器的具体代码,供大家参考,具体内容如下

服务器端:部署在Tomcat上,直接在myEclipse上开发即可

package com;

import java.io.BufferedInputStream;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

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.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class upload extends HttpServlet {

private String transerFileName ;

/**

* Constructor of the object.

*/

public upload() {

super();

}

/**

* Destruction of the servlet.

*/

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

/**

* The doGet method of the servlet.

*

* This method is called when a form has its tag value method equals to get.

*

* @param request

* the request send by the client to the server

* @param response

* the response send by the server to the client

* @throws ServletException

* if an error occurred

* @throws IOException

* if an error occurred

*/

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println(""-//W3C//DTD HTML 4.01 Transitional//EN\">");

out.println("");

out.println("

A Servlet");

out.println("

");

out.print(" This is ");

out.print(this.getClass());

out.println(", using the GET method");

out.println(" ");

out.println("");

out.flush();

out.close();

}

/**

* The doPost method of the servlet.

*

* This method is called when a form has its tag value method equals to

* post.

*

* @param request

* the request send by the client to the server

* @param response

* the response send by the server to the client

* @throws ServletException

* if an error occurred

* @throws IOException

* if an error occurred

*/

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

// /response.setHeader("Content-Type",

// "application/x-www-form-urlencoded; charset=GBK");

PrintWriter out = response.getWriter();

request.setCharacterEncoding("utf-8");这句至关重要,不然中文的文件名称显示乱码

// 创建文件项目工厂对象

DiskFileItemFactory factory = new DiskFileItemFactory();

// 设置文件上传路径

//String upload = this.getServletContext().getRealPath("/upload/");

String upload="F:\\upload";

// 获取系统默认的临时文件保存路径,该路径为Tomcat根目录下的temp文件夹

// String temp = System.getProperty("java.io.tmpdir");

// 设置缓冲区大小为 500M

factory.setSizeThreshold(1024 * 1024 * 500);// //缓冲区设置太大会上传失败

// 设置临时文件夹为temp

// factory.setRepository(new File(temp));

factory.setRepository(new File(upload));

// 用工厂实例化上传组件,ServletFileUpload 用来解析文件上传请求

ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

// 解析结果放在List中

List list;

try {

list = servletFileUpload.parseRequest(request);

for (FileItem item : list) {

String name = item.getFieldName();

InputStream is = item.getInputStream();

if (name.contains("file")) {

try {

InputStream input = item.getInputStream();

String itemName = item.getName();

String fileName = itemName.substring(

itemName.lastIndexOf("\\") + 1,

itemName.length());

FileOutputStream output = new FileOutputStream(

new File(

"F:\\upload\\"

+ fileName));

byte[] buf = new byte[102400];

int length = 0;

while ((length = input.read(buf)) != -1) {

output.write(buf, 0, length);

}

input.close();

output.close();

} catch (Exception e) {

e.printStackTrace();

}

out.write("success");

out.flush();

out.close();

}// / if (name.contains("file"))

}// /for

} catch (FileUploadException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

/**

* Initialization of the servlet.

*

* @throws ServletException

* if an error occurs

*/

public void init() throws ServletException {

// Put your code here

}

}

手机端:

package com.example;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.UnsupportedEncodingException;

import org.apache.http.client.methods.HttpPost;

import android.app.Activity;

import android.os.Bundle;

import android.os.Environment;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

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 TextView uploadInfo;

private Button button1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

uploadInfo = (TextView) findViewById(R.id.upload_info);

button1 = (Button) findViewById(R.id.button1);

button1.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO 自动生成的方法存根

uploadFile();

}

});

}// /onCreate

private void uploadFile() {

// new Thread(new Runnable() {不能使用线程

//

// @Override

// public void run() {

// TODO 自动生成的方法存根

// 服务器端地址

String url = "http://192.168.0.105:8080/upload/servlet/upload";

// 手机端要上传的文件,首先要保存你手机上存在该文件

// String filePath = Environment.getExternalStorageDirectory() +

// "/1delete/1.jpg";

// String filePath ="/sdcard/1delete/1.jpg"; ///可以

// String filePath ="/sdcard/11/软工大作业.ppt";///可以

// String filePath ="/sdcard/音乐/许嵩-千古.mp3";别忘了/sdcard开头,,可以

// /String filePath ="/sdcard/相机/22222.mp4"; ///30M 不可以

String filePath = "/sdcard/音乐/爱的勇气.mp3";

Log.i("filePath", filePath);

AsyncHttpClient httpClient = new AsyncHttpClient();

httpClient.setTimeout(60 * 60 * 1000);

RequestParams param = new RequestParams();

try {

param.put("file", new File(filePath));

httpClient.post(url, param, new AsyncHttpResponseHandler() {

@Override

public void onStart() {

super.onStart();

uploadInfo.setText("正在上传...");

}

@Override

public void onSuccess(String arg0) {

super.onSuccess(arg0);

Log.i("ck", "success>" + arg0);

if (arg0.equals("success")) {

Toast.makeText(MainActivity.this, "上传成功!", 1000).show();

}

uploadInfo.setText(arg0);

}

@Override

public void onFailure(Throwable arg0, String arg1) {

super.onFailure(arg0, arg1);

uploadInfo.setText("上传失败!");

}

});

} catch (FileNotFoundException e) {

e.printStackTrace();

Toast.makeText(MainActivity.this, "上传文件不存在!", 1000).show();

}

// }

// }).start();

}

}

package="com.example"

android:versionCode="1"

android:versionName="1.0" >

android:minSdkVersion="8"

android:targetSdkVersion="17" />

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

android:name=".MainActivity"

android:label="@string/app_name" >

1e98b8f1b53e22d304f750e6f2334a68.png

73d5602e73fcfa3124708144eb3c2260.png

c898f645cf5130d43fb1b1438e28fdd5.png

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值