okhttp上传文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ljw124213/article/details/52317518

1.先做好准备工作,在网上下载okhttp的jar包,放到工程的libs目录下:

下载地址:http://download.csdn.net/detail/ljw124213/9613065

2.对于android端开发的人员来说,只需完成client端的代码,然后调用服务器端的接口拼接到url后面,即可以完成文件的上传工作。这里先给出client端的代码:

package cn.edu.qianfeng;


import java.io.IOException;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;


public class TestFileUpload {
	public static void main(String[] args) {
		//创建OkHttpClient对象(前提是导入了okhttp.jar和okio.jar)
		OkHttpClient client = new OkHttpClient();
		//封装请求数据
		RequestBody body = new MultipartBuilder().addFormDataPart("user", "lu")  //提交普通表单数据
							 .addFormDataPart("file1", "1.txt", RequestBody.create(null, "D:\1.txt"))
							 .build();
		//封装request,使用okhttp框架上传数据只能使用post提交方式
		Request request = new Request.Builder().url("http://localhost:8080/uploadserver/FileUploadServlet")
				                       .post(body)
				                       .build();
		//执行请求    enqueue:异步执行
		client.newCall(request).enqueue(new Callback() {
			//请求成功会执行此方法
			@Override
			public void onResponse(Response response) throws IOException {
				if (response.isSuccessful()) {
					//服务器端把返回的结果封装在了body()中
					byte[] result = response.body().bytes();
					System.out.println(new String(result));
				}
			}
			//请求失败会执行此方法
			@Override
			public void onFailure(Request request, IOException e) {
				e.printStackTrace();
			}
		});
	}
}


3.下面是服务器端的servlet代码,可以用来测试上面的代码,需要下载两个上传文件的jar包:

下载地址:http://download.csdn.net/detail/ljw124213/9613084

package cn.edu.lu;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
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 {

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		String uploadFileName = ""; // 上传的文件名
		String fieldName = ""; // 表单字段元素的name属性值
		// 请求信息中的内容是否是multipart类型
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		// 上传文件的存储路径(服务器文件系统上的绝对文件路径)
		// String uploadFilePath =
		// request.getSession().getServletContext().getRealPath("\\test" );
		if (isMultipart) {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			try {
				// 解析form表单中所有文件
				List<FileItem> items = upload.parseRequest(request);
				Iterator<FileItem> iter = items.iterator();
				while (iter.hasNext()) { // 依次处理每个文件
					FileItem item = (FileItem) iter.next();
					if (item.isFormField()) { // 普通表单字段
						fieldName = item.getFieldName(); // 表单字段的name属性值
						if (fieldName.equals("user")) {
							// 输出表单字段的值
							System.out.print(item.getString("UTF-8") + "上传了文件.");
						}
					} else { // 文件表单字段
						String fileName = item.getName();
						if (fileName != null && !fileName.equals("")) {
							File fullFile = new File(item.getName());
							File saveFile = new File("D:\\test", fullFile.getName());
							item.write(saveFile);
							uploadFileName = fullFile.getName();
							System.out.println("上传的文件名是:" + uploadFileName);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

4.上传文件的html代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<div style="text-align: center;">	
		<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
			<p>用户名:<input type="text" name="user"></p>
			<p>密码<input type="file" name="file1"></p>
			<p><input type="submit" value="上传"></p>
		</form>
	</div>
</body>
</html>

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页