1.服务端采用的是.net的WEBAPI接口。

2.android多文件上传。

以下为核心代码:

 package com.example.my.androidupload;

 import android.util.Log;

 import java.io.File;
import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry; import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils; /**
* Created by wz on 2016/04/19.
*/
public class HttpClientUtil {
public final static String Method_POST = "POST";
public final static String Method_GET = "GET"; /**
* multipart/form-data类型的表单提交
*
* @param form 表单数据
*/
public static String submitForm(MultipartForm form) {
// 返回字符串
String responseStr = ""; // 创建HttpClient实例
/* HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient httpClient = httpClientBuilder.build();*/
// CloseableHttpClient httpClient= HttpClients.createDefault(); HttpClient httpClient = new DefaultHttpClient();
try {
// 实例化提交请求
HttpPost httpPost = new HttpPost(form.getAction()); // 创建MultipartEntityBuilder
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); Log.e("HttpClientUtil", "111");
// 追加普通表单字段
Map<String, String> normalFieldMap = form.getNormalField();
for (Iterator<Entry<String, String>> iterator = normalFieldMap.entrySet().iterator(); iterator.hasNext(); ) {
Entry<String, String> entity = iterator.next();
entityBuilder.addPart(entity.getKey(), new StringBody(entity.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
}
Log.e("HttpClientUtil", "222");
// 追加文件字段
Map<String, File> fileFieldMap = form.getFileField();
for (Iterator<Entry<String, File>> iterator = fileFieldMap.entrySet().iterator(); iterator.hasNext(); ) {
Entry<String, File> entity = iterator.next();
entityBuilder.addPart(entity.getKey(), new FileBody(entity.getValue()));
}
Log.e("HttpClientUtil", "333");
// 设置请求实体
httpPost.setEntity(entityBuilder.build());
Log.e("HttpClientUtil", "444");
// 发送请求
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
// 取得响应数据
HttpEntity resEntity = response.getEntity();
Log.e("HttpClientUtil", "结果:" + Integer.toString(statusCode));
if (200 == statusCode) {
if (resEntity != null) {
responseStr = EntityUtils.toString(resEntity);
}
}
} catch (Exception e) {
System.out.println("提交表单失败,原因:" + e.getMessage());
} finally {
try {
httpClient.getConnectionManager().shutdown();
} catch (Exception ex) {
}
}
return responseStr;
} /**
* 表单字段Bean
*/
public class MultipartForm implements Serializable {
/**
* 序列号
*/
private static final long serialVersionUID = -2138044819190537198L; /**
* 提交URL
**/
private String action = ""; /**
* 提交方式:POST/GET
**/
private String method = "POST"; /**
* 普通表单字段
**/
private Map<String, String> normalField = new LinkedHashMap<String, String>(); /**
* 文件字段
**/
private Map<String, File> fileField = new LinkedHashMap<String, File>(); public String getAction() {
return action;
} public void setAction(String action) {
this.action = action;
} public String getMethod() {
return method;
} public void setMethod(String method) {
this.method = method;
} public Map<String, String> getNormalField() {
return normalField;
} public void setNormalField(Map<String, String> normalField) {
this.normalField = normalField;
} public Map<String, File> getFileField() {
return fileField;
} public void setFileField(Map<String, File> fileField) {
this.fileField = fileField;
} public void addFileField(String key, File value) {
fileField.put(key, value);
} public void addNormalField(String key, String value) {
normalField.put(key, value);
}
} }

调用:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button mBtnUpload;

    @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_upload: {
new Thread(new Runnable() {
@Override
public void run() {
HttpClientUtil httpClient = new HttpClientUtil();
HttpClientUtil.MultipartForm form = httpClient.new MultipartForm();
//设置form属性、参数
form.setAction("http://192.168.1.5:9001/api/Mobile/FileUpload/UploadFile");
String path= Environment.getExternalStorageDirectory().getPath()+"/DCIM" + "/20151120_051052.jpg";
Log.e("11", path);
File file = new File(path);
form.addFileField("file", file);
form.addNormalField("ID", "301201604");
String resultcode = httpClient.submitForm(form); Log.e("上传结果:",resultcode);
}
}).start(); break;
}
}
} @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnUpload = (Button) findViewById(R.id.btn_upload);
mBtnUpload.setOnClickListener(this);
}
}

服务端代码(由.net WEBAPI开发):

     /// <summary>
/// 附件上传
/// </summary>
[RoutePrefix("api/Mobile/FileUpload")]
public class FileUploadController : ApiController
{
static readonly string UploadFolder = "/UpLoad/ApiUpload";
static readonly string ServerUploadFolder = HttpContext.Current.Server.MapPath(UploadFolder); #region 上传文件-文件信息不保存到数据库
/// <summary>
/// 上传文件-文件信息不保存到数据库
/// </summary>
/// <returns>返回文件信息</returns>
[HttpPost]
[Route("UploadFile")]
public async Task<List<FileResultDTO>> UploadFile()
{
Log.Info("UploadFile", "进入"); // 验证这是一个HTML表单文件上传请求
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
Log.Info("UploadFile", "error01");
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
} // Create a stream provider for setting up output streams
MultipartFormDataStreamProvider streamProvider = new RenamingMultipartFormDataStreamProvider(ServerUploadFolder);
// Read the MIME multipart asynchronously content using the stream provider we just created.
await Request.Content.ReadAsMultipartAsync(streamProvider);
Log.Info("UploadFile", "进入01");
List<FileResultDTO> itemList = new List<FileResultDTO>();
foreach (MultipartFileData file in streamProvider.FileData)
{
Log.Info("UploadFile", "进入02"); FileInfo fileInfo = new FileInfo(file.LocalFileName); FileResultDTO item = new FileResultDTO();
var sLocalFileName = file.LocalFileName;
string fileName = sLocalFileName.Substring(sLocalFileName.LastIndexOf("\\") + , sLocalFileName.Length - sLocalFileName.LastIndexOf("\\") - ); item.ID = Guid.NewGuid();
item.FileName = file.Headers.ContentDisposition.FileName;
item.ServerFileName = fileInfo.Name;
item.FileSize = fileInfo.Length;
item.FilePath = UploadFolder;
item.FullFilePath = ServerUploadFolder;
item.ContentType = file.Headers.ContentType.MediaType.ToString();
item.UploadTime = DateTime.Now; itemList.Add(item);
}
Log.Info("UploadFile", "进入03");
return itemList;
}
#endregion #region 上传文件-文件信息会保存到数据库 /// <summary>
/// 上传文件-文件信息会保存到数据库
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("UploadFileToServer")]
public IHttpActionResult UploadFileToServer()
{
//验证是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
} List<AttachmentDTO> list = new List<AttachmentDTO>();
string devId = "";
for (int i = ; i < HttpContext.Current.Request.Files.Count; i++)
{
HttpPostedFile file = HttpContext.Current.Request.Files[i]; string sFileName = "ST_M_" + Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName);
string path = AppDomain.CurrentDomain.BaseDirectory + ServerUploadFolder + "/"; file.SaveAs(Path.Combine(path, sFileName)); AttachmentDTO entity = new AttachmentDTO();
devId = HttpContext.Current.Request["DevId"].ToString();
string ForeignID = HttpContext.Current.Request["ForeignID"].ToString(); entity.ForeignID = ForeignID;
entity.FileName = sFileName;
entity.FilePath = ServerUploadFolder;
entity.UploadTime = DateTime.Now;
entity.ContentType = file.ContentType;
entity.FileSize = file.ContentLength;
entity.CreatedTime = DateTime.Now; list.Add(entity);
} MobileBL.GetInstance().InsertAttachment(devId, list);
return Ok(true);
}
#endregion
}
public class RenamingMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public string Root { get; set; }
//public Func<FileUpload.PostedFile, string> OnGetLocalFileName { get; set; } public RenamingMultipartFormDataStreamProvider(string root)
: base(root)
{
Root = root;
} public override string GetLocalFileName(HttpContentHeaders headers)
{
string filePath = headers.ContentDisposition.FileName; // Multipart requests with the file name seem to always include quotes.
if (filePath.StartsWith(@"""") && filePath.EndsWith(@""""))
filePath = filePath.Substring(, filePath.Length - ); var filename = Path.GetFileName(filePath);
var extension = Path.GetExtension(filePath);
var contentType = headers.ContentType.MediaType; return "ST_M_" + Guid.NewGuid() + extension;
} }

Android Studiod代码下载:点击下载

参考:http://www.cnblogs.com/fly100/articles/3492525.html

Android实现表单提交,webapi接收的更多相关文章

  1. JSP表单提交与接收

    JSP表单提交与接收 在Myeclipse中新建web project,在webroot中新建userRegist1.jsp,代码如下 <%@ page contentType="te ...

  2. 基于Http原理实现Android的图片上传和表单提交

    版权声明:本文由张坤  原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/794875001483009140 来源:腾云阁  ...

  3. 在IOS设备上POST提交form表单,后台接收不到值怎么办?

    原文:https://blog.csdn.net/xhaimail/article/details/90440029 最近在工作上遇到一个奇葩问题,在Android和Windows平台上做请求时参数都 ...

  4. asp.net.mvc 中form表单提交控制器的2种方法和控制器接收页面提交数据的4种方法

    MVC中表单form是怎样提交? 控制器Controller是怎样接收的? 1..cshtml 页面form提交 (1)普通方式的的提交

  5. SpringMVC中使用bean来接收form表单提交的参数时的注意点

    这是前辈们对于SpringMVC接收表单数据记录下来的总结经验: SpringMVC接收页面表单参数 springmvc请求参数获取的几种方法 下面是我自己在使用时发现的,前辈们没有记录的细节和注意点 ...

  6. Java Web开发总结(三) —— request接收表单提交中文参数乱码问题

    1.以POST方式提交表单中文参数的乱码问题 <%@ page language="java" import="java.util.*" pageEnco ...

  7. request接收表单提交数据及其中文参数乱码问题

    一.request接收表单提交数据: getParameter(String)方法(常用) getParameterValues(String name)方法(常用) getParameterMap( ...

  8. input from 表单提交 使用 属性 disabled=&quot;disabled&quot; 后台接收不到name=&quot;username&quot;的值

    input from 表单提交 使用 属性 disabled="disabled" 后台接收不到name="username"的值

  9. c#WebApi使用form表单提交excel,实现批量写入数据库

    思路:用户点击下载模板按钮,获取到excel模板,然后向里面填写数据保存.from表单提交的时候选择保存好的excel,实现数据的批量导入过程 先把模板放在服务器的项目目录下面:如 模板我一般放在:F ...

随机推荐

  1. RPM安装卸载软件

    1.安装 rpm -i 需要安装的包文件名 举例如下: rpm -i example.rpm 安装 example.rpm 包: rpm -iv example.rpm 安装 example.rpm ...

  2. [失败]SystemTap和火焰图(Flame Graph)

    本文参考http://blog.51cto.com/xuclv/1184517 SystemTap简介: SystemTap provides free software (GPL) infrastr ...

  3. python值解析excel

    原文:http://blog.csdn.net/tomatoandbeef/article/details/52253578 一.安装python和xlrd模块 python下载地址,安装好后要配置环 ...

  4. linux下python3离线加载nltk_data,不用nltk.download()

    在不能上网的服务器上把nltk_data关联到python3,已经安装anaconda3所以不需要安装nltk,环境是linux 首先没有nltk_data在使用nltk会报错 LookupError ...

  5. django-admin:command not found的解决办法

    django-admin:command not found的解决办法 找到django-admin的路径 绝对路径  然后用命令行运行 python3 /usr/local/python3/lib/ ...

  6. Maven配置本地仓库

    当我们在myeclipse中update maven时可能会报错User setting file does not exist C:\Users\lenevo\.m2\setting.xml,以致于 ...

  7. 5月23日Google就宣布了Chrome 36 beta

    对于开发人员来说,本次更新的重点还有element.animate().HTML Imports.Object.observe()的引入,以及一个改进后的throttled async touchmo ...

  8. gain 基尼系数

    转至:http://blog.csdn.net/bitcarmanlee/article/details/51488204 在信息论与概率统计学中,熵(entropy)是一个很重要的概念.在机器学习与 ...

  9. 使用.sig签名验证文件

    Linux下载文件的时候,由于网络等原因,下载的文件可能不完整,对于别有心机的人可以更改文件,这就需要我们对文件的完整性进行验证.这里以securityonion-14.04.5.2.iso为例进行验 ...

  10. 关于mybatis框架的总结【转载】

    原文地址:https://www.cnblogs.com/xiaotie666/p/LiujinMybatisSummary.html 此文为转载.请支持原作者. 最近在学习MyBatis框架,我在这 ...