标签:
import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class UploadUtil { private static final String TAG = "UploadUtil"; public static String upload(String uploadUrl, String uploadFile) { String fileName = ""; int pos = uploadFile.lastIndexOf("/"); if (pos >= 0) { fileName = uploadFile.substring(pos + 1); } String end = "\r\n"; String Hyphens = "--"; String boundary = "WUm4580jbtwfJhNp7zi1djFEO3wNNm"; try { URL url = new URL(uploadUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream ds = new DataOutputStream(conn.getOutputStream()); ds.writeBytes(Hyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=\"file1\";filename=\"" + fileName + "\"" + end); ds.writeBytes(end); FileInputStream fStream = new FileInputStream(uploadFile); // 每次写入1024字节 int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; // 将文件数据写入到缓冲区 while((length = fStream.read(buffer)) != -1) { ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(Hyphens + boundary + Hyphens + end); fStream.close(); ds.flush(); // 获取返回内容 InputStream is = conn.getInputStream(); int ch; StringBuffer b = new StringBuffer(); while ((ch = is.read()) != -1) { b.append((char) ch); } ds.close(); return "SUCC"; } catch (Exception e) { e.printStackTrace(); return "上传失败:" + e.getMessage(); } } }
import java.io.File; import com.example.exmupload.MainActivity; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.RequestParams; import android.util.Log; public class AsyncUtil { private static final String TAG = "AsyncUtil"; public static String upload(final MainActivity act, String uploadServlet, String filePath, boolean isBinary) { try { //服务端的commons-fileupload只支持multipart/form-data方式 //application/octet-stream表示任意的二进制文件,包括图片、音频、视频、压缩文件等等 String contentType = "application/octet-stream"; //String contentType = "multipart/form-data"; RequestParams params = new RequestParams(); if (isBinary == true) { params.put("file", new File(filePath), contentType); } else { params.put("file", new File(filePath)); } Log.d(TAG, "contentType="+contentType); AsyncHttpClient client = new AsyncHttpClient(); //AsyncHttpResponseHandle不在ui线程运行,不能直接操作ui //如果在此处定义AsyncHttpResponseHandle对象,则运行报错: //java.lang.IllegalArgumentException: Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead. client.post(uploadServlet, params, act.mAsyncHandler); return "uploadByFile"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } // //下面代码在MainActivity.java中定义 // public AsyncHttpResponseHandler mAsyncHandler = new AsyncHttpResponseHandler() { // @Override // public void onSuccess(int status, Header[] headers, byte[] data) { // String result = "文件上传成功!"; // Message msg = Message.obtain(); // msg.what = ASYNC; // msg.obj = result; // mHandler.sendMessage(msg); // } // // @Override // public void onFailure(int status, Header[] headers, byte[] data, Throwable e) { // String result = "文件上传失败!"+e.getMessage(); // Message msg = Message.obtain(); // msg.what = ASYNC; // msg.obj = result; // mHandler.sendMessage(msg); // } // }; }
import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.example.exmupload.MainActivity; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.http.Multipart; import retrofit2.http.PartMap; import retrofit2.http.POST; import android.util.Log; import android.webkit.MimeTypeMap; public class RetrofitUtil { private static final String TAG = "RetrofitUtil"; public interface ApiInterface { //这里的POST是不带ip也不带域名的地址,下面uploadHost才带ip/域名和端口,如http://192.168.0.212:8080/ @Multipart @POST("UploadTest/uploadServlet") Call<ResponseBody> upload(@PartMap Map<String, RequestBody> params); } public static void upload(final MainActivity act, String uploadHost, String filePath) { File file1 = new File(filePath); Retrofit retrofit = new Retrofit.Builder().baseUrl(uploadHost).build(); ApiInterface apiService = retrofit.create(ApiInterface.class); // 获取文件真实的内容类型 // String mimeType = MimeTypeMap.getSingleton() // .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(file1.getPath())); // RequestBody fileBody = RequestBody.create(MediaType.parse(mimeType), filePath); RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), filePath); Map<String, RequestBody> params = new HashMap<>(); // 如果要上传多个文件,可对该Map对象进行put操作 params.put("file\"; filename=\"" + file1.getName() + "", fileBody); Call<ResponseBody> call = apiService.upload(params); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { try { String jsonString = new String(response.body().bytes()); // 这就是返回的json字符串了。 Log.d(TAG, "onResponse succ : "+jsonString); act.notify(act.RETROFIT, "onResponse succ "+jsonString); } catch (IOException e) { e.printStackTrace(); act.notify(act.RETROFIT, "onResponse "+e.getMessage()); } } @Override public void onFailure(Call<ResponseBody> call, Throwable throwable) { Log.d(TAG, "onFailure : "+throwable.getMessage()); act.notify(act.RETROFIT, "onFailure "+throwable.getMessage()); } }); } }
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.Writer; import java.util.Iterator; 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.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UploadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("request.getContentType()="+request.getContentType()); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); Writer o = response.getWriter(); //首先判断Content-Type是不是multipart/form-data。同时也判断了form的提交方式是不是post if (ServletFileUpload.isMultipartContent(request)) { request.setCharacterEncoding("utf-8"); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload DiskFileItemFactory factory = new DiskFileItemFactory(); //设置文件存放的临时文件夹,这个文件夹要真实存在 File fileDir = new File("../webapps/"); if (fileDir.isDirectory() && fileDir.exists()==false) { fileDir.mkdir(); } factory.setRepository(fileDir); //设置最大占用的内存 factory.setSizeThreshold(1024000); //创建ServletFileUpload对象 ServletFileUpload sfu = new ServletFileUpload(factory); sfu.setHeaderEncoding("utf-8"); //设置单个文件最大值byte sfu.setFileSizeMax(102400000); //所有上传文件的总和最大值byte sfu.setSizeMax(204800000); List<FileItem> items = null; try { items = sfu.parseRequest(request); System.out.println("items.size()="+items.size()); } catch(Exception e) { e.printStackTrace(); } Iterator<FileItem> iter = items==null?null:items.iterator(); //文件上传后存放的路径目录 File dir = new File("D:/"); if (dir.exists()==false) { dir.mkdirs(); } while (iter!=null && iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //如果传过来的是普通的表单域 System.out.print("普通的表单域:"); System.out.print(new String(item.getFieldName()) + " "); System.out.println(new String(item.getString("UTF-8"))); } else if (!item.isFormField()) { //文件域 System.out.println("源文件:" + item.getName()); String fileName = item.getName(); if (fileName.indexOf("\\") >= 0) { fileName = item.getName().substring(item.getName().lastIndexOf("\\")); } BufferedInputStream in = new BufferedInputStream(item.getInputStream()); BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(new File(dir.getAbsolutePath()+ fileName))); Streams.copy(in, out, true); o.write("文件上传成功"); } } } else { System.out.println("表单的Content-Type错误"); } } }
import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; public class FTPUtil { private static String mUurl; private static String mPort; private static String mUsername; private static String mPassword; public static void setUser(String url, String port, String username, String password) { mUurl = url; mPort = port; mUsername = username; mPassword = password; } public static String upload(String remotePath, String filePath, String fileName) { FTPClient ftpClient = new FTPClient(); String result = "SUCC"; try { ftpClient.connect(mUurl, Integer.parseInt(mPort)); boolean loginResult = ftpClient.login(mUsername, mPassword); int returnCode = ftpClient.getReplyCode(); if (loginResult && FTPReply.isPositiveCompletion(returnCode)) { //登录成功 ftpClient.makeDirectory(remotePath); // 设置上传目录 ftpClient.changeWorkingDirectory(remotePath); ftpClient.setBufferSize(1024); ftpClient.setControlEncoding("UTF-8"); ftpClient.enterLocalPassiveMode(); FileInputStream fis = new FileInputStream(filePath + fileName); ftpClient.storeFile(fileName, fis); } else { //登录失败 result = "FAIL"; } } catch (IOException e) { e.printStackTrace(); result = "FTP客户端出错!" + e.getMessage(); } finally { try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); result = "关闭FTP连接发生异常!" + e.getMessage(); } } return result; } }
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; import java.util.Vector; import android.util.Log; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.ChannelSftp.LsEntry; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; public class SFTPUtil { private static final String TAG = "SFTPUtil"; public static int SUCC = 0; public static int FAIL = -1; //连接sftp服务器 public static ChannelSftp connect(String host, int port, String username, String password) { ChannelSftp sftp = null; try { JSch jsch = new JSch(); jsch.getSession(username, host, port); Session session = jsch.getSession(username, host, port); session.setPassword(password); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; Log.d(TAG, "Connected to " + host + "."); } catch (Exception e) { e.printStackTrace(); } return sftp; } //上传文件 public static String upload(ChannelSftp sftp, String directory, String uploadFile) { try { sftp.cd(directory); File file = new File(uploadFile); sftp.put(new FileInputStream(file), file.getName()); Log.d(TAG, "Upload succ. " + uploadFile); return "SUCC"; } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } //下载文件 public static int download(ChannelSftp sftp, String directory, String downloadFile, String saveFile) { try { sftp.cd(directory); File file = new File(saveFile); sftp.get(downloadFile, new FileOutputStream(file)); Log.d(TAG, "Download succ. " + downloadFile); return SUCC; } catch (Exception e) { e.printStackTrace(); return FAIL; } } //删除文件 public static int delete(ChannelSftp sftp, String directory, String deleteFile) { try { sftp.cd(directory); sftp.rm(deleteFile); Log.d(TAG, "Delete succ. " + deleteFile); return SUCC; } catch (Exception e) { e.printStackTrace(); return FAIL; } } //列出目录下的文件 public static Vector<?> listFiles(ChannelSftp sftp, String directory) throws SftpException { //Vector容器内部保存的是LsEntry类型对象。 return sftp.ls(directory); } }
import java.util.Map; import org.apache.http.Header; import com.aqi00.lib.dialog.FileSelectFragment; import com.aqi00.lib.dialog.FileSelectFragment.FileSelectCallbacks; import com.example.exmupload.util.AsyncUtil; import com.example.exmupload.util.FTPUtil; import com.example.exmupload.util.RetrofitUtil; import com.example.exmupload.util.SFTPUtil; import com.example.exmupload.util.UploadUtil; import com.jcraft.jsch.ChannelSftp; import com.loopj.android.http.AsyncHttpResponseHandler; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener,FileSelectCallbacks { private static final String TAG = "MainActivity"; private static TextView tv_filename; private Button btn_select; private Button btn_upload; private Button btn_async; private Button btn_retrofit; private Button btn_ftp; private Button btn_sftp; private static TextView tv_result; public static String mUploadHost = "http://192.168.0.212:8080/"; public static String mUploadService = "UploadTest/uploadServlet"; private String mServletUrl = mUploadHost + mUploadService; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv_filename = (TextView) findViewById(R.id.tv_filename); btn_select = (Button) findViewById(R.id.btn_select); btn_upload = (Button) findViewById(R.id.btn_upload); btn_async = (Button) findViewById(R.id.btn_async); btn_retrofit = (Button) findViewById(R.id.btn_retrofit); btn_ftp = (Button) findViewById(R.id.btn_ftp); btn_sftp = (Button) findViewById(R.id.btn_sftp); tv_result = (TextView) findViewById(R.id.tv_result); btn_select.setOnClickListener(this); btn_upload.setOnClickListener(this); btn_async.setOnClickListener(this); btn_retrofit.setOnClickListener(this); btn_ftp.setOnClickListener(this); btn_sftp.setOnClickListener(this); } @Override public void onClick(View v) { String file_path = tv_filename.getText().toString().trim(); if (v.getId() == R.id.btn_select) { FileSelectFragment.show(this, new String[]{"jpg","png","gif","txt"}, null); return; } if (file_path.length() <= 0) { Toast.makeText(this, "请选择要上传的文件", Toast.LENGTH_LONG).show(); return; } if (v.getId() == R.id.btn_upload) { tv_result.setText("开始HttpURLConnection上传"); new ConnnectionThread(file_path).start(); } else if (v.getId() == R.id.btn_async) { tv_result.setText("开始async上传"); new AsyncThread(file_path).start(); } else if (v.getId() == R.id.btn_retrofit) { tv_result.setText("开始retrofit上传"); new RetrofitThread(file_path).start(); } else if (v.getId() == R.id.btn_ftp) { new FTPThread(file_path).start(); } else if (v.getId() == R.id.btn_sftp) { new SFTPThread(file_path).start(); } } public void notify(int type, String message) { Message msg = Message.obtain(); msg.what = type; msg.obj = message; mHandler.sendMessage(msg); } private class ConnnectionThread extends Thread { private String mFilePath; public ConnnectionThread(String file_path) { mFilePath = file_path; } @Override public void run() { String result = UploadUtil.upload(mServletUrl, mFilePath); MainActivity.this.notify(COMMON, "upload :" + result); } } private class AsyncThread extends Thread { private String mFilePath; public AsyncThread(String file_path) { mFilePath = file_path; } @Override public void run() { String result = AsyncUtil.upload(MainActivity.this, mServletUrl, mFilePath, true); MainActivity.this.notify(ASYNC, "upload :" + result); } } public AsyncHttpResponseHandler mAsyncHandler = new AsyncHttpResponseHandler() { @Override public void onSuccess(int status, Header[] headers, byte[] data) { MainActivity.this.notify(ASYNC, "文件上传成功!"); } @Override public void onFailure(int status, Header[] headers, byte[] data, Throwable e) { MainActivity.this.notify(ASYNC, "文件上传失败!"+e.getMessage()); } }; private class RetrofitThread extends Thread { private String mFilePath; public RetrofitThread(String file_path) { mFilePath = file_path; } @Override public void run() { RetrofitUtil.upload(MainActivity.this, mUploadHost, mFilePath); } } private class FTPThread extends Thread { private String mFilePath; public FTPThread(String file_path) { mFilePath = file_path; } @Override public void run() { String filepath = mFilePath.substring(0, mFilePath.lastIndexOf("/")+1); String filename = mFilePath.substring(mFilePath.lastIndexOf("/")+1); FTPUtil.setUser("172.16.16.146", "21", "testftp", "testftp"); String result = FTPUtil.upload("/home/testftp", filepath, filename); MainActivity.this.notify(FTP, result); } } private class SFTPThread extends Thread { private String mFilePath; public SFTPThread(String file_path) { mFilePath = file_path; } @Override public void run() { ChannelSftp sftp = SFTPUtil.connect("172.16.16.133", 22, "oracle", "oracle"); String result = SFTPUtil.upload(sftp, "/home/oracle", mFilePath); MainActivity.this.notify(SFTP, result); } } public int COMMON = 0; public int ASYNC = 1; public int RETROFIT = 2; public int FTP = 3; public int SFTP = 4; @SuppressLint("HandlerLeak") public Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { String result = (String) msg.obj; if (msg.what == COMMON) { tv_result.setText(tv_result.getText().toString()+"\n"+result); } else if (msg.what == ASYNC) { tv_result.setText(tv_result.getText().toString()+"\n"+result); } else if (msg.what == RETROFIT) { tv_result.setText(tv_result.getText().toString()+"\n"+result); } else if (msg.what == FTP) { showTip("FTP文件上传结果:"+result); } else if (msg.what == SFTP) { showTip("sftp文件上传结果:"+result); } } }; private void showTip(String desc) { Toast.makeText(getApplicationContext(), desc, Toast.LENGTH_SHORT).show(); } @Override public void onConfirmSelect(String absolutePath, String fileName, Map<String, Object> map_param) { String path = absolutePath + "/" + fileName; tv_filename.setText(path); } @Override public boolean isFileValid(String absolutePath, String fileName, Map<String, Object> map_param) { return true; } }
标签:
原文地址:http://blog.csdn.net/aqi00/article/details/51859280