• c# WebApi POST请求同时包含数据及其文件


      原因:创建.net WebApi的接口API。IIS作为服务端。安卓作为客户端发送json文件及其文件。

                 Android端使用xUtils3.0实现文件上传

      java代码:

    //要传递给服务器的json格式参数
    JSONObject json = new JSONObject();
            try {
                json.put("devId", id);
                json.put("devName", devName);
                json.put("keyWord", keyWord);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //构建RequestParams对象,传入请求的服务器地址URL
            RequestParams params = new RequestParams(Constants.UPLOAD_FILE);
            params.setAsJsonContent(true);
            List<KeyValue> list = new ArrayList<>();
            list.add(new KeyValue("file", new File(filePah)));
            list.add(new KeyValue("parameters", json.toString()));
            MultipartBody body = new MultipartBody(list, "UTF-8");
            params.setRequestBody(body);
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    LogUtil.e("请求结果:" + result);
                }
    
                @Override
                public void onFinished() {
                    //上传完成
                }
    
                @Override
                public void onCancelled(CancelledException cex) {
                //取消上传
                }
    
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                //上传失败
                    LogUtil.e("请求失败:" + ex.toString());
    
                }
            });

    .net WebApi代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using System.Data.Entity;
    using Newtonsoft.Json;
    using System.Configuration;
    
    namespace AndroidWebAPI.Controllers
    {
        public class AddInfoController : ApiController
        {
                   public IEnumerable<string> PostAddInfo()
            {
                     
         
                if (!Request.Content.IsMimeMultipartContent("form-data"))
                {                
                    return "请求内容不是表单形式";            
                }         
                if (HttpContext.Current.Request.Files.Count >0)
                {
                    try
                    {
                        
                        var file = HttpContext.Current.Request.Files[0];     
                        string fname = DateTime.Now.ToString("yyyyMMddHHmmssfff") + file.FileName;
                      
                        string SavePath = HttpContext.Current.Server.MapPath(string.Format("~/{0}", "File"));
                       
                        if (Directory.Exists(SavePath))
                        {
                            Directory.CreateDirectory(SavePath);
                        }            
                        string fullPathUrl = Path.Combine(SavePath, fname);                  
                        file.SaveAs(fullPathUrl);
                        videoFileName = fname;
                    }
                    catch (Exception ex)
                    {                         
                    }
                }
                      
                return PBimLogic.AddProblemListInfo(Plm, videoFileName);           
              
            }
    
    
    
    
        }
    }

    c# 创建控制台模拟表单上传数据与文件.

    创建HttpUpload类

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Net;
    using System.Text;
    
    namespace HttpTest
    {
        public class HttpUpload
        {
            private ArrayList bytesArray;
            private Encoding encoding = Encoding.UTF8;
            private string boundary = String.Empty;
    
            public HttpUpload()
            {
                bytesArray = new ArrayList();
                string flag = DateTime.Now.Ticks.ToString("x");
                boundary = "---------------------------" + flag;
            }
    
            /// <summary>
            /// 合并请求数据
            /// </summary>
            /// <returns></returns>
            private byte[] MergeContent()
            {
                int length = 0;
                int readLength = 0;
                string endBoundary = "--" + boundary + "--
    ";
                byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);
    
                bytesArray.Add(endBoundaryBytes);
    
                foreach (byte[] b in bytesArray)
                {
                    length += b.Length;
                }
    
                byte[] bytes = new byte[length];
    
                foreach (byte[] b in bytesArray)
                {
                    b.CopyTo(bytes, readLength);
                    readLength += b.Length;
                }
    
                return bytes;
            }
    
            /// <summary>
            /// 上传
            /// </summary>
            /// <param name="requestUrl">请求url</param>
            /// <param name="responseText">响应</param>
            /// <returns></returns>
            public bool Upload(String requestUrl, out String responseText)
            {
                WebClient webClient = new WebClient();
                webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
    
                byte[] responseBytes;
                byte[] bytes = MergeContent();
    
                try
                {
                    responseBytes = webClient.UploadData(requestUrl, bytes);
                    responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
                    return true;
                }
                catch (WebException ex)
                {
                    Stream responseStream = ex.Response.GetResponseStream();
                    responseBytes = new byte[ex.Response.ContentLength];
                    responseStream.Read(responseBytes, 0, responseBytes.Length);
                }
                responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
                return false;
            }
    
            /// <summary>
            /// 设置表单数据字段
            /// </summary>
            /// <param name="fieldName">字段名</param>
            /// <param name="fieldValue">字段值</param>
            /// <returns></returns>
            public void SetFieldValue(String fieldName, String fieldValue)
            {
                string httpRow = "--" + boundary + "
    Content-Disposition: form-data; name="{0}"
    
    {1}
    ";
                string httpRowData = String.Format(httpRow, fieldName, fieldValue);
    
                bytesArray.Add(encoding.GetBytes(httpRowData));
            }
    
            /// <summary>
            /// 设置表单文件数据
            /// </summary>
            /// <param name="fieldName">字段名</param>
            /// <param name="filename">字段值</param>
            /// <param name="contentType">内容内型</param>
            /// <param name="fileBytes">文件字节流</param>
            /// <returns></returns>
            public void SetFieldValue(String fieldName, String filename, String contentType, Byte[] fileBytes)
            {
                string end = "
    ";
                string httpRow = "--" + boundary + "
    Content-Disposition: form-data; name="{0}"; filename="{1}"
    Content-Type: {2}
    
    ";
                string httpRowData = String.Format(httpRow, fieldName, filename, contentType);
    
                byte[] headerBytes = encoding.GetBytes(httpRowData);
                byte[] endBytes = encoding.GetBytes(end);
                byte[] fileDataBytes = new byte[headerBytes.Length + fileBytes.Length + endBytes.Length];
    
                headerBytes.CopyTo(fileDataBytes, 0);
                fileBytes.CopyTo(fileDataBytes, headerBytes.Length);
                endBytes.CopyTo(fileDataBytes, headerBytes.Length + fileBytes.Length);
    
                bytesArray.Add(fileDataBytes);
            }
        }
    }

    控制台调用:

    using System;
    using System.IO;
    using System.Text;
    
    namespace HttpTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
    
                try
                {
                    var httpUpload = new HttpUpload();
                    string txtJsonData= File.ReadAllText(@"D:TestHttpTestHttpTestHttpTestJsonData.txt", Encoding.UTF8);
                    httpUpload.SetFieldValue("parameters", txtJsonData);
             
                    string path = @"D:TestHttpTestHttpTestHttpTestTest.txt";
                    FileStream fspdf = new FileStream(path, FileMode.Open);
                    byte[] fileBytepdf = new byte[fspdf.Length];
                    fspdf.Read(fileBytepdf, 0, fileBytepdf.Length);
                    fspdf.Close();
                    var pdfName = path.Substring(path.LastIndexOf("\") + 1);
                    httpUpload.SetFieldValue(pdfName, pdfName, "application/octet-stream", fileBytepdf);
                    string responStr = "";
                    //string _apiUrl = @"http://localhost:51013/api/AddInfo";
                    string _apiUrl = @"http://192.168.2.1:10000//api/AddInfo";
                    bool suc = httpUpload.Upload(_apiUrl, out responStr);
                }
                catch (Exception ex)
                {
    
                    throw ex; 
                }
    
                Console.ReadLine();
            }
        }
    }
  • 相关阅读:
    保持简单----纪念丹尼斯•里奇(Dennis Ritchie)
    转:有关retina和HiDPI那点事
    Powershell 学习
    Windows与Linux共享文件夹互相访问
    你知道C语言为什么会有“_”(下划线)吗?
    百度公共DNS
    AXIS2的一些认识
    待整理
    java复习汇总之面试篇
    落网歌曲图片下载
  • 原文地址:https://www.cnblogs.com/TBW-Superhero/p/9042255.html
Copyright © 2020-2023  润新知