c# - 将文件从 Html 表单(多部分/表单数据)作为流上传到 WCF REST 服务而不流式传输整个表单的输入?

标签 c# rest file-upload

我目前在将文件从 Html 上传到我的休息服务 (WCF REST) 时遇到问题。上传文件时,我想连同文件的内容一起发送标题和说明等信息。

所以,我创建了一个这样的测试表单:

<form id="testForm" action="http://localhost.:1576/NotepadService.svc/Note/91f6413c-4d72-42ca-a0f3-38df15759fc9/Attachment" method="POST" enctype="multipart/form-data">
        <table>
            <tr><td>Title:</td><td><input type="text" name="Title"></td></tr>
            <tr><td>Description:</td><td><input type="text" name="Description"></td></tr>
            <tr><td>Filename:</td><td><input type="text" name="Filename"></td></tr>
            <tr><td>File:</td><td><input type="file" name="Contents"></td></tr>
            <tr><td/><td><input type="submit" value="Send"></td></tr>
        </table>
    </form>

服务器端,我想把它翻译成这个方法:

[OperationContract]
        [WebInvoke(
            BodyStyle = WebMessageBodyStyle.Bare,
            Method = "POST",
            UriTemplate = "/Note/{noteId}/Attachment")]
        [Description("Add an attachment to a Note.")]
        void AddAttachmentToNote(string noteId, AttachmentRequestDto attachmentRequestDto);

AttachmentRequestDto 定义为

[DataContract]
    public class AttachmentRequestDto
    {
         [DataMember]
         public string Title { get; set; }
         [DataMember]
         public string Description { get; set; }
         [DataMember]
         public string Filename { get; set; }
         [DataMember]
         public Stream Contents { get; set; }
    }

所以,长话短说,我想以字符串值的形式获取标题和描述,同时以流的形式获取文件的内容。这似乎不起作用,因为 html 表单会将表单的所有内容(还有标题和说明)连同文件的内容一起放入流中。因此,将我的 REST 方法定义为

[OperationContract]
        [WebInvoke(
            BodyStyle = WebMessageBodyStyle.Bare,
            Method = "POST",
            UriTemplate = "/Note/{noteId}/Attachment")]
        [Description("Add an attachment to a Note.")]
        void AddAttachmentToNote(string noteId, Stream formContents);

有效,但随后我需要解析流以获取我的所有数据(与我实际想要做的相比,这不是一个好的方法)。

也许我需要定义两种不同的服务方法,一种只接受文件,另一种接受文件的详细信息?然而,这意味着我的业务规则(需要标题 + 需要文件内容)应该以不同方式验证(因为 REST 是无状态的)。

可能值得一提的是:我需要将文件的内容保存在数据库中,而不是文件系统中。

有人对此有意见吗?我有点坚持...

谢谢!

最佳答案

请查找一些代码,这些代码可能会帮助您在对 REST 服务的单次调用中传递文件及其详细信息:

首先,您需要一个名为 MultipartParser 的东西,如下所示:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace SampleService
{
    public class MultipartParser
    {
        private byte[] requestData;
        public MultipartParser(Stream stream)
        {
            this.Parse(stream, Encoding.UTF8);
            ParseParameter(stream, Encoding.UTF8);
        }

        public MultipartParser(Stream stream, Encoding encoding)
        {
            this.Parse(stream, encoding);
        }

        private void Parse(Stream stream, Encoding encoding)
        {
            this.Success = false;

            // Read the stream into a byte array
            byte[] data = ToByteArray(stream);
            requestData = data;

            // Copy to a string for header parsing
            string content = encoding.GetString(data);

            // The first line should contain the delimiter
            int delimiterEndIndex = content.IndexOf("\r\n");

            if (delimiterEndIndex > -1)
            {
                string delimiter = content.Substring(0, content.IndexOf("\r\n"));

                // Look for Content-Type
                Regex re = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
                Match contentTypeMatch = re.Match(content);

                // Look for filename
                re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
                Match filenameMatch = re.Match(content);

                // Did we find the required values?
                if (contentTypeMatch.Success && filenameMatch.Success)
                {
                    // Set properties
                    this.ContentType = contentTypeMatch.Value.Trim();
                    this.Filename = filenameMatch.Value.Trim();

                    // Get the start & end indexes of the file contents
                    int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;

                    byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
                    int endIndex = IndexOf(data, delimiterBytes, startIndex);

                    int contentLength = endIndex - startIndex;

                    // Extract the file contents from the byte array
                    byte[] fileData = new byte[contentLength];

                    Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);

                    this.FileContents = fileData;
                    this.Success = true;
                }
            }
        }

        private void ParseParameter(Stream stream, Encoding encoding)
        {
            this.Success = false;

            // Read the stream into a byte array
            byte[] data;
            if (requestData.Length == 0)
            {
                data = ToByteArray(stream);
            }
            else { data = requestData; }
            // Copy to a string for header parsing
            string content = encoding.GetString(data);

            // The first line should contain the delimiter
            int delimiterEndIndex = content.IndexOf("\r\n");

            if (delimiterEndIndex > -1)
            {
                string delimiter = content.Substring(0, content.IndexOf("\r\n"));
                string[] splitContents = content.Split(new[] {delimiter}, StringSplitOptions.RemoveEmptyEntries);
                foreach (string t in splitContents)
                {
                    // Look for Content-Type
                    Regex contentTypeRegex = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
                    Match contentTypeMatch = contentTypeRegex.Match(t);

                    // Look for name of parameter
                    Regex re = new Regex(@"(?<=name\=\"")(.*)");
                    Match name = re.Match(t);

                    // Look for filename
                    re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
                    Match filenameMatch = re.Match(t);

                    // Did we find the required values?
                    if (name.Success || filenameMatch.Success)
                    {
                        // Set properties
                        //this.ContentType = name.Value.Trim();
                        int startIndex;
                        if (filenameMatch.Success)
                        {
                            this.Filename = filenameMatch.Value.Trim();
                        }
                        if(contentTypeMatch.Success)
                        {
                            // Get the start & end indexes of the file contents
                            startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
                        }
                        else
                        {
                            startIndex = name.Index + name.Length + "\r\n\r\n".Length;
                        }

                        //byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
                        //int endIndex = IndexOf(data, delimiterBytes, startIndex);

                        //int contentLength = t.Length - startIndex;
                        string propertyData = t.Substring(startIndex - 1, t.Length - startIndex);
                        // Extract the file contents from the byte array
                        //byte[] paramData = new byte[contentLength];

                        //Buffer.BlockCopy(data, startIndex, paramData, 0, contentLength);

                        MyContent myContent = new MyContent();
                        myContent.Data = encoding.GetBytes(propertyData);
                        myContent.StringData = propertyData;
                        myContent.PropertyName = name.Value.Trim();

                        if (MyContents == null)
                            MyContents = new List<MyContent>();

                        MyContents.Add(myContent);
                        this.Success = true;
                    }
                }
            }
        }

        private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex)
        {
            int index = 0;
            int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);

            if (startPos != -1)
            {
                while ((startPos + index) < searchWithin.Length)
                {
                    if (searchWithin[startPos + index] == serachFor[index])
                    {
                        index++;
                        if (index == serachFor.Length)
                        {
                            return startPos;
                        }
                    }
                    else
                    {
                        startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
                        if (startPos == -1)
                        {
                            return -1;
                        }
                        index = 0;
                    }
                }
            }

            return -1;
        }

        private byte[] ToByteArray(Stream stream)
        {
            byte[] buffer = new byte[32768];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }

        public List<MyContent> MyContents { get; set; }

        public bool Success
        {
            get;
            private set;
        }

        public string ContentType
        {
            get;
            private set;
        }

        public string Filename
        {
            get;
            private set;
        }

        public byte[] FileContents
        {
            get;
            private set;
        }
    }

    public class MyContent
    {
        public byte[] Data { get; set; }
        public string PropertyName { get; set; }
        public string StringData { get; set; }
    }
}

现在定义您的 REST 方法,如下所示:

[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
AttachmentRequestDto AddAttachmentToNote(Stream stream);

现在上述方法的实现如下所示:

public AttachmentRequestDto AddAttachmentToNote(Stream stream)
        {
            MultipartParser parser = new MultipartParser(stream);
            if(parser != null && parser.Success)
            {
                foreach (var content in parser.MyContents)
                {
                    // Observe your string here which is a serialized version of your file or the object being passed. Based on the string do the necessary action.
                    string str = Encoding.UTF8.GetString(content.Data);

                }
            }

            return new AttachmentRequestDto();
        }

我的 AttachmentRequestDto 看起来如下所示:

[DataContract]
    public class AttachmentRequestDto
    {
         [DataMember]
         public string Title { get; set; }
         [DataMember]
         public string Description { get; set; }
         [DataMember]
         public string Filename { get; set; }
    }

现在我从客户端执行一个 POST,如下所示:

Image image = Image.FromFile("C:\\Users\\Guest\\Desktop\\sample.png");
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] imageArray = ms.ToArray();
ms.Close();

AttachmentRequestDto objAttachmentRequestDto = new AttachmentRequestDto();
objAttachmentRequestDto.Title = "Sample";
objAttachmentRequestDto.Description = "Sample book";
objAttachmentRequestDto.FileName = "SampleBook.png";

var serializer = new DataContractSerializer(typeof(AttachmentRequestDto));
var ms = new MemoryStream();
serializer.WriteObject(ms, objAttachmentRequestDto);
ms.Position = 0;
var reader = new StreamReader(ms);
string requestBody = reader.ReadToEnd();

var client = new RestClient();            
client.BaseUrl = "http://localhost/SampleService/Service1.svc";
var request = new RestRequest(method) { DateFormat = DataFormat.Xml.ToString(), Resource = resourceUrl };
if(requestBody !=null)
      request.AddParameter("objAttachmentRequestDto", requestBody);
request.AddFile("stream", image, "Array.png");
var response = client.Execute(request);

我确实为上面的代码使用了一个名为 RESTSharp 的第三方 dll。 .

一旦在服务器上,MultipartParser 会识别您的请求边界以拆分必要的内容,然后您可以决定如何处理每个拆分的内容(保存到文件、数据库等)

只需确保您具有上述内容的适当配置条目以及为 webHttpBinding 设置的 dataContractSerializer 属性和 readerQuotas。

注意:如果需要,可以进一步重构 MultipartParser。

关于c# - 将文件从 Html 表单(多部分/表单数据)作为流上传到 WCF REST 服务而不流式传输整个表单的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9734941/

相关文章:

c# - 为同一方法的两次调用设置两个不同的返回值

java - RESTful web 服务无法在 Tomcat 8.0.5 上启动

ruby-on-rails - 您是否需要弄乱Rails的 "routes.rb"文件?

html - 无法在 React 中上传文件时附加到 formData 对象

java - 在GAE java中使用inputstream上传文件

Delphi XE ISAPI WebBroker 文件上传

C#、 Entity Framework 、自增

c# - 如何在 .NET Core 中逐行下载文件?

c# - Fluent NHibernate Reveal 不使用给定的属性名

java - 在同一个 Spring Boot 应用程序中休息服务和 Web 服务