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. 性能基准测试:KVM大战Xen

    编译自:http://major.io/2014/06/22/performance-benchmarks-kvm-vs-xen/作者: Major Hayden原创:LCTT https://lin ...

  2. js 各种距离

    网页可见区域宽  document.body.clientWidth  网页可见区域高  document.body.clientHeight  网页可见区域宽(包括边线的宽)  document.b ...

  3. VsCode中vim插件剪切板等问题

    剪切板共享 这个挺重要的,否则每次右键菜单复制粘贴会奔溃的. 在用户设置中添加: "vim.useSystemClipboard": true, 光标的变化 我觉得这个也重要,毕竟 ...

  4. MyBait 符号大于 小于理解

    EQ 就是 EQUAL等于 NQ 就是 NOT EQUAL不等于 GT 就是 GREATER THAN大于 LT 就是 LESS THAN小于 GE 就是 GREATER THAN OR EQUAL ...

  5. PO BO VO DTO POJO DAO概念及其作用

    J2EE开发中大量的专业缩略语很是让人迷惑,尤其是跟一些高手讨论问题的时候,三分钟就被人家满口的专业术语喷晕了,PO VO BO DTO POJO DAO,一大堆的就来了(听过老罗对这种现象的批判的朋 ...

  6. JAVA 非对称加密工具

    import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.securi ...

  7. 【读书笔记】《Python_Cookbook3》第一章:数据结构和算法

      Python提供了多样化有用的内建数据结构,例如列表.集合.字典.大多数时候,这些结构的使用比较简单,然后,一些关于搜索.排序.过滤的常见问题经常出现.本章节的目标是讨论常见的数据结构,以及涉及到 ...

  8. MyEclipse10.0 配置 Tomcat1.7

    1 首先 从网上下载Tomcat1.7,然后放到本机目录. 2 然后在MyEclipse10.0菜单Preferences 指向Tomcat的路径,我本机路径是 D:\Program Files (x ...

  9. adf 日志输出

    1,选中ViewController或是Model,在属性框中,做如下配置,run/debug后可以看到日志信息中,将adf的整个执行过程很详细的打印出来了. 在每个项目的Project proper ...

  10. [Selenium]Click element under a hidden element

    Description: Find out the DDL in Treegrid, but cannot click on it.Because the element is under a hid ...