android通過servlet上傳文件到服務器
本文實例為大家分享了android通過servlet上傳文件到服務器的具體代碼,供大家參考,具體內容如下
服務器端:部署在Tomcat上,直接在myEclipse上開發(fā)即可
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. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* 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");////這句至關重要,不然中文的文件名稱顯示亂碼
// 創(chuàng)建文件項目工廠對象
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設置文件上傳路徑
//String upload = this.getServletContext().getRealPath("/upload/");
String upload="F:\\upload";
// 獲取系統(tǒng)默認的臨時文件保存路徑,該路徑為Tomcat根目錄下的temp文件夾
// String temp = System.getProperty("java.io.tmpdir");
// 設置緩沖區(qū)大小為 500M
factory.setSizeThreshold(1024 * 1024 * 500);// //緩沖區(qū)設置太大會上傳失敗
// 設置臨時文件夾為temp
// factory.setRepository(new File(temp));
factory.setRepository(new File(upload));
// 用工廠實例化上傳組件,ServletFileUpload 用來解析文件上傳請求
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
// 解析結果放在List中
List<FileItem> 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. <br>
*
* @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/軟工大作業(yè).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();
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<!-- 使用網絡功能所需權限 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- SDK離線地圖和cache功能需要讀寫外部存儲器 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<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>



以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Android開發(fā)MediaCodec和lamemp3多段音頻截取拼接
這篇文章主要為大家介紹了Android開發(fā)使用MediaCodec和lamemp3實現多段音頻截取拼接的編程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-04-04
android TextView多行文本(超過3行)使用ellipsize屬性無效問題的解決方法
這篇文章介紹了android TextView多行文本(超過3行)使用ellipsize屬性無效問題的解決方法,有需要的朋友可以參考一下2013-09-09
Android RecyclerView上拉加載和下拉刷新(基礎版)
這篇文章主要為大家詳細介紹了Android RecyclerView上拉加載和下拉刷新的相實現方法,內容簡單,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02
Android4.4下MediaProvider無法向外置SD卡中文件寫數據的解決方法
這篇文章主要介紹了Android4.4下MediaProvider無法向外置SD卡中文件寫數據的解決方法,實例分析了Android4.4下針對讀寫限制的修改技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10
android studio 3.6.1升級后如何處理 flutter問題
這篇文章主要介紹了android-studio-3.6.1升級后 flutter問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
android 關于利用簽名的SHA1進行安全校驗的方法之一(推薦)
下面小編就為大家?guī)硪黄猘ndroid 關于利用簽名的SHA1進行安全校驗的方法之一(推薦)。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01
Android 解決sqlite無法創(chuàng)建新表的問題
這篇文章主要介紹了Android 解決sqlite無法創(chuàng)建新表的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05

