安卓端代码
/** 上传文字加图片 */
public void postDataFile(String serverUrl, String fileurl, String data) {
Log.e("test", "load" + serverUrl);
Log.e("test", "load" + fileurl);
Log.e("test", "load" + data);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(serverUrl);
MultipartEntity mpEntity = new MultipartEntity();
try {
File file = new File(fileurl);
FileBody fileBody = new FileBody(file);
mpEntity.addPart("file", fileBody);
mpEntity.addPart(
"data",
new StringBody(data, Charset
.forName(org.apache.http.protocol.HTTP.UTF_8)));
post.setEntity(mpEntity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(),
"utf-8");
ho.handleEvent(content);//回调函数
}
Log.e("test", "IsOk");
} catch (Exception e) {
Log.e("test", "出错了:"+e);
} finally {
if (mpEntity != null) {
try {
mpEntity.consumeContent();
} catch (UnsupportedOperationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
client.getConnectionManager().shutdown();
}
}
服务端代码
</pre><pre class="java" name="code"><pre class="java" name="code">public class SaveDataFile extends HttpServlet {
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isHaveData = ServletFileUpload.isMultipartContent(request);
if (isHaveData) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
// 普通文本信息处理
String paramName = item.getFieldName();
String paramValue = item.getString();
System.out.println(paramName + ":" + paramValue);
} else {
// 上传文件信息处理
String fileName = item.getName();
byte[] data = item.get();
String filePath = getServletContext().getRealPath(
"/files")
+ "/" + fileName;
FileOutputStream fos = new FileOutputStream(filePath);
fos.write(data);
fos.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
response.getWriter().write("isok");
}
原文 http://www.apkbus.com/android-93080-1-1.html
最后
以上就是复杂缘分最近收集整理的关于HttpClient-MultipartEntity上传文字和图像的全部内容,更多相关HttpClient-MultipartEntity上传文字和图像内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复