首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >.NET:使用http将文件上载到服务器

.NET:使用http将文件上载到服务器
EN

Stack Overflow用户
提问于 2018-01-18 03:32:33
回答 2查看 5.2K关注 0票数 14

我有一个运行状态的.php脚本,它点击一个.csv并上传一个/多个文件.csv类型,其中发送了一个唯一的token (在AFAIK中)。下面是工作片段:

PHP:

代码语言:javascript
运行
AI代码解释
复制
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$ch = curl_init('http://demo.schooling.net/school/attendance');

$DirPath = "E:/Uploads/";

$ZKFiles=array();

if ($dh = opendir($DirPath)) 
{
    while (($file = readdir($dh)) !== false) 
    {
        if ($file == '.' || $file == '..') 
        {
            continue;
        }
        $ZKFiles[]='@'.$DirPath.$file;       
    }
    closedir($dh);
}
if(!empty($ZKFiles))
{
    // Assign POST data
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch,CURLOPT_FAILONERROR,false);
    curl_setopt_custom_postfields($ch, array('Files[]'=>$ZKFiles,'token'=>'fe60313b0edfdfaf757f9744815454545'));
    // Execute the handle
    $execResult=curl_exec($ch);
    if($execResult=== false)
    {
        echo 'Curl error: ' . curl_error($ch);
    }
    else
    {
        echo 'Operation completed without any errors';
        echo $execResult;
    }

}


function curl_setopt_custom_postfields($ch, $postfields, $headers = null) {
    $algos = hash_algos();
    $hashAlgo = null;
    foreach ( array('sha1', 'md5') as $preferred ) {
        if ( in_array($preferred, $algos) ) {
            $hashAlgo = $preferred;
            break;
        }
    }
    if ( $hashAlgo === null ) { list($hashAlgo) = $algos; }
    $boundary =
        '----------------------------' .
        substr(hash($hashAlgo, 'cURL-php-multiple-value-same-key-support' . microtime()), 0, 12);

    $body = array();
    $crlf = "\r\n";
    $fields = array();
    foreach ( $postfields as $key => $value ) {
        if ( is_array($value) ) {
            foreach ( $value as $v ) {
                $fields[] = array($key, $v);
            }
        } else {
            $fields[] = array($key, $value);
        }
    }

    //print_r($fields);die();
    foreach ( $fields as $field ) {
        list($key, $value) = $field;
        if ( strpos($value, '@') === 0 ) {
            preg_match('/^@(.*?)$/', $value, $matches);
            list($dummy, $filename) = $matches;
            $body[] = '--' . $boundary;
            $body[] = 'Content-Disposition: form-data; name="' . $key . '"; filename="' . basename($filename) . '"';
            $body[] = 'Content-Type: application/octet-stream';
            $body[] = '';
            $body[] = file_get_contents($filename);
        } else {
            $body[] = '--' . $boundary;
            $body[] = 'Content-Disposition: form-data; name="' . $key . '"';
            $body[] = '';
            $body[] = $value;
        }
    }
    $body[] = '--' . $boundary . '--';
    $body[] = '';
    //print_r($body);die();
    $contentType = 'multipart/form-data; boundary=' . $boundary;
    $content = join($crlf, $body);
    $contentLength = strlen($content);

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Length: ' . $contentLength,
        'Expect: 100-continue',
        'Content-Type: ' . $contentType,
    ));
    //echo $content;die();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
}
?>

为了在.NET中实现这一点,我已经尝试过(所有可能的方法)。

第一种方法(使用WebClient):

代码语言:javascript
运行
AI代码解释
复制
[HttpPost]
public void SendFiles()
{
    string fileToUpload = @"E:\Uploads\demo.csv";
    string url ="http://demo.schooling.net/school/attendance";
    using (var client = new WebClient())
    {
        //sending token and then uplaoding file
        System.Collections.Specialized.NameValueCollection postData =
                        new System.Collections.Specialized.NameValueCollection()
        {
            { "token", "fe60313b0edfdfaf757f9744815454545" }
        };
        string pagesource = Encoding.UTF8.GetString(client.UploadValues(url, "POST", postData));

        //string authInfo = Convert.ToBase64String(Encoding.Default.GetBytes("fe60313b0edfdfaf757f9744815454545"));
        client.Headers["token"] = "fe60313b0edfdfaf757f9744815454545";
        client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
        byte[] result = client.UploadFile(url, fileToUpload);
        string responseAsString = Encoding.Default.GetString(result);
    }
}

这没有将令牌发送到url,因此页面被重定向到登录页。

第二种方法(使用.NET MultipartDataContent)

代码语言:javascript
运行
AI代码解释
复制
string fileUpload = @"E:\Uploads\demo.csv";
string uri = "http://demo.schooling.net/school/attendance";
//Using built-in MultipartFormDataContent
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form1 = new MultipartFormDataContent();
FileStream fs = System.IO.File.OpenRead(fileUpload);
var streamContent = new StreamContent(fs);

var Content = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
Content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
//Add token here first
form1.Add(new StringContent("fe60313b0edfdfaf757f9744815454545"), "token");
form1.Add(Content, "csv", Path.GetFileName(fileUpload));
var response = httpClient.PostAsync(uri, form1).Result;

这失败了,所以它导致我第三次尝试。(没有寄出任何标记)

第三种方法(使用cutom MultipartForm描述的这里)

代码语言:javascript
运行
AI代码解释
复制
//Using Custom MultipartForm
MultipartForm form = new MultipartForm(url);
form.SetField("token", "fe60313b0edfdfaf757f9744815454545");

form.SendFile(@"E:\Uploads\demo.csv");

MultiPartForm.cs:

代码语言:javascript
运行
AI代码解释
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Net;

namespace Helpers
{
    /// <summary>
    /// Allow the transfer of data files using the W3C's specification
    /// for HTTP multipart form data. Microsoft's version has a bug
    /// where it does not format the ending boundary correctly.
    /// Original version written by Gregory Prentice : gregoryp@norvanco.com
    /// See: http://www.c-sharpcorner.com/UploadFile/gregoryprentice/DotNetBugs12062005230632PM/DotNetBugs.aspx
    /// </summary>
    public class MultipartForm
    {
        /// <summary>
        /// Holds any form fields and values that you
        /// wish to transfer with your data.
        /// </summary>
        private Hashtable coFormFields;

        /// <summary>
        /// Used mainly to avoid passing parameters to other routines.
        /// Could have been local to sendFile().
        /// </summary>
        protected HttpWebRequest coRequest;

        /// <summary>
        /// Used if we are testing and want to output the raw
        /// request, minus http headers, out to a file.
        /// </summary>
        private Stream coFileStream;

        /// <summary>
        /// Difined to build the form field data that is being
        /// passed along with the request.
        /// </summary>
        private static string CONTENT_DISP = "Content-Disposition: form-data; name=";

        /// <summary>
        /// Allows you to specify the specific version of HTTP to use for uploads.
        /// The dot NET stuff currently does not allow you to remove the continue-100 header
        /// from 1.1 and 1.0 currently has a bug in it where it adds the continue-100. MS
        /// has sent a patch to remove the continue-100 in HTTP 1.0.
        /// </summary>
        public Version TransferHttpVersion { get; set; }

        /// <summary>
        /// Used to change the content type of the file being sent.
        /// Currently defaults to: text/xml. Other options are
        /// text/plain or binary
        /// </summary>
        public string FileContentType { get; set; }

        /// <summary>
        /// Initialize our class for use to send data files.
        /// </summary>
        /// <param name="url">The web address of the recipient of the data transfer.</param>
        public MultipartForm(string url)
        {
            URL = url;
            coFormFields = new Hashtable();
            ResponseText = new StringBuilder();
            BufferSize = 1024 * 10;
            BeginBoundary = "ou812--------------8c405ee4e38917c";
            TransferHttpVersion = HttpVersion.Version11;
            //FileContentType = "text/xml";
            FileContentType = "text/csv";
        }
        //---------- BEGIN PROPERTIES SECTION ----------
        private string _BeginBoundary;
        /// <summary>
        /// The string that defines the begining boundary of
        /// our multipart transfer as defined in the w3c specs.
        /// This method also sets the Content and Ending
        /// boundaries as defined by the w3c specs.
        /// </summary>
        public string BeginBoundary
        {
            get { return _BeginBoundary; }
            set
            {
                _BeginBoundary = value;
                ContentBoundary = "--" + BeginBoundary;
                EndingBoundary = ContentBoundary + "--";
            }
        }

        /// <summary>
        /// The string that defines the content boundary of
        /// our multipart transfer as defined in the w3c specs.
        /// </summary>
        protected string ContentBoundary { get; set; }

        /// <summary>
        /// The string that defines the ending boundary of
        /// our multipart transfer as defined in the w3c specs.
        /// </summary>
        protected string EndingBoundary { get; set; }

        /// <summary>
        /// The data returned to us after the transfer is completed.
        /// </summary>
        public StringBuilder ResponseText { get; set; }

        /// <summary>
        /// The web address of the recipient of the transfer.
        /// </summary>
        public string URL { get; set; }

        /// <summary>
        /// Allows us to determine the size of the buffer used
        /// to send a piece of the file at a time out the IO
        /// stream. Defaults to 1024 * 10.
        /// </summary>
        public int BufferSize { get; set; }

        //---------- END PROPERTIES SECTION ----------

        /// <summary>
        /// Used to signal we want the output to go to a
        /// text file verses being transfered to a URL.
        /// </summary>
        /// <param name="path"></param>
        public void SetFilename(string path)
        {
            coFileStream = new System.IO.FileStream(path, FileMode.Create, FileAccess.Write);
        }
        /// <summary>
        /// Allows you to add some additional field data to be
        /// sent along with the transfer. This is usually used
        /// for things like userid and password to validate the
        /// transfer.
        /// </summary>
        /// <param name="key">The form field name</param>
        /// <param name="str">The form field value</param>
        public void SetField(string key, string str)
        {
            coFormFields[key] = str;
        }
        /// <summary>
        /// Determines if we have a file stream set, and returns either
        /// the HttpWebRequest stream of the file.
        /// </summary>
        /// <returns></returns>
        public virtual Stream GetStream()
        {
            Stream stream;
            if (null == coFileStream)
                stream = coRequest.GetRequestStream();
            else
                stream = coFileStream;
            return stream;
        }
        /// <summary>
        /// Here we actually make the request to the web server and
        /// retrieve it's response into a text buffer.
        /// </summary>
        public virtual void GetResponse()
        {
            if (null == coFileStream)
            {
                Stream stream;
                WebResponse response;
                try
                {
                    response = coRequest.GetResponse();
                }
                catch (WebException web)
                {
                    response = web.Response;
                }
                if (null != response)
                {
                    stream = response.GetResponseStream();
                    StreamReader sr = new StreamReader(stream);
                    string str;
                    ResponseText.Length = 0;
                    while ((str = sr.ReadLine()) != null)
                        ResponseText.Append(str);
                    response.Close();
                }
                else
                    throw new Exception("MultipartForm: Error retrieving server response");
            }
        }
        /// <summary>
        /// Transmits a file to the web server stated in the
        /// URL property. You may call this several times and it
        /// will use the values previously set for fields and URL.
        /// </summary>
        /// <param name="filename">The full path of file being transfered.</param>
        public void SendFile(string filename)
        {
            // The live of this object is only good during
            // this function. Used mainly to avoid passing
            // around parameters to other functions.
            coRequest = (HttpWebRequest)WebRequest.Create(URL);
            // Set use HTTP 1.0 or 1.1.
            coRequest.ProtocolVersion = TransferHttpVersion;
            coRequest.Method = "POST";
            coRequest.ContentType = "multipart/form-data; boundary=" + BeginBoundary;
            coRequest.Headers.Add("Cache-Control", "no-cache");
            coRequest.KeepAlive = true;
            string strFields = GetFormfields();
            string strFileHdr = GetFileheader(filename);
            string strFileTlr = GetFiletrailer();
            FileInfo info = new FileInfo(filename);
            coRequest.ContentLength = strFields.Length +
              strFileHdr.Length +
              strFileTlr.Length +
              info.Length;
            System.IO.Stream io;
            io = GetStream();
            WriteString(io, strFields);
            WriteString(io, strFileHdr);
            this.WriteFile(io, filename);
            WriteString(io, strFileTlr);
            GetResponse();
            io.Close();
            // End the life time of this request object.
            coRequest = null;
        }
        /// <summary>
        /// Mainly used to turn the string into a byte buffer and then
        /// write it to our IO stream.
        /// </summary>
        /// <param name="stream">The io stream for output.</param>
        /// <param name="str">The data to write.</param>
        public void WriteString(Stream stream, string str)
        {
            byte[] postData = System.Text.Encoding.ASCII.GetBytes(str);
            stream.Write(postData, 0, postData.Length);
        }
        /// <summary>
        /// Builds the proper format of the multipart data that
        /// contains the form fields and their respective values.
        /// </summary>
        /// <returns>The data to send in the multipart upload.</returns>
        public string GetFormfields()
        {
            string str = "";
            IDictionaryEnumerator myEnumerator = coFormFields.GetEnumerator();
            while (myEnumerator.MoveNext())
            {
                str += ContentBoundary + "\r\n" +
                  CONTENT_DISP + '"' + myEnumerator.Key + "\"\r\n\r\n" +
                  myEnumerator.Value + "\r\n";
            }
            return str;
        }
        /// <summary>
        /// Returns the proper content information for the
        /// file we are sending.
        /// </summary>
        /// <remarks>
        /// Hits Patel reported a bug when used with ActiveFile.
        /// Added semicolon after sendfile to resolve that issue.
        /// Tested for compatibility with IIS 5.0 and Java.
        /// </remarks>
        /// <param name="filename"></param>
        /// <returns></returns>
        public string GetFileheader(string filename)
        {
            return ContentBoundary + "\r\n" +
              CONTENT_DISP +
              "\"sendfile\"; filename=\"" +
              Path.GetFileName(filename) + "\"\r\n" +
              "Content-type: " + FileContentType + "\r\n\r\n";
        }
        /// <summary>
        /// Creates the proper ending boundary for the multipart upload.
        /// </summary>
        /// <returns>The ending boundary.</returns>
        public string GetFiletrailer()
        {
            return "\r\n" + EndingBoundary;
        }
        /// <summary>
        /// Reads in the file a chunck at a time then sends it to the
        /// output stream.
        /// </summary>
        /// <param name="stream">The io stream to write the file to.</param>
        /// <param name="filename">The name of the file to transfer.</param>
        public void WriteFile(Stream stream, string filename)
        {
            using (FileStream readIn = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                readIn.Seek(0, SeekOrigin.Begin); // move to the start of the file
                byte[] fileData = new byte[BufferSize];
                int bytes;
                while ((bytes = readIn.Read(fileData, 0, BufferSize)) > 0)
                {
                    // read the file data and send a chunk at a time
                    stream.Write(fileData, 0, bytes);
                }
            }
        }
    }
}

没有运气,但有很大的宽容,第四次尝试(在这种方法中也没有发送任何标记)。

第四种方法(使用HttpClient)

代码语言:javascript
运行
AI代码解释
复制
using (var client = new HttpClient())
{
    using (var multipartFormDataContent = new MultipartFormDataContent())
    {
        var values = new[]
        {

    new KeyValuePair<string, string>("token", "fe60313b0edfdfaf757f9744815454545")
     //other values
};

        foreach (var keyValuePair in values)
        {
            multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
                String.Format("\"{0}\"", keyValuePair.Key));
        }

        multipartFormDataContent.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(@"E:\\Uploads\\demo.csv")),
            '"' + "File" + '"',
            '"' + "democollege.csv" + '"');
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", "fe60313b0edfdfaf757f9744815454545");
        var requestUri = "http://demo.schooling.net/school/attendance";
        var result = client.PostAsync(requestUri, multipartFormDataContent).Result;
    }
}

这也让我失望了,也没有任何标记,最终也没有上传任何文件。

第五种方法(使用HttpWebRequest)

代码语言:javascript
运行
AI代码解释
复制
   public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.AllowAutoRedirect = false;
           // wr.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
            wr.Headers.Add("Authorization", "Basic " + "fe60313b0edfdfaf757f9744815454545");
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
            Stream rs = wr.GetRequestStream();
            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, paramName, file, contentType);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);
            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();
            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();
            WebResponse wresp = null;
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                var result = reader2.ReadToEnd();
            }
            catch (Exception ex)
            {
               // System.Windows.MessageBox.Show("Error occurred while converting file", "Error!");
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }
        }

然后调用该方法:

代码语言:javascript
运行
AI代码解释
复制
string fileToUpload = @"E:\Uploads\demo.csv";
                string url = "http://demo.schooling.net/school/attendance";
                NameValueCollection nvc = new NameValueCollection();
                nvc.Add("token", "fe60313b0edfdfaf757f9744815454545");
                HttpUploadFile(url, fileToUpload, "file", "text/csv", nvc);

这也失败了,尽管我正在获取表单数据。(图片附后,使用上述尝试之一)

通过在PHP脚本中添加这一行:

代码语言:javascript
运行
AI代码解释
复制
 ...$body[] = '';
    print_r($body);die();

我可以在浏览器中看到这一点:

代码语言:javascript
运行
AI代码解释
复制
Array ( [0] => Array 
( [0] => Files[] 
[1] => @E:/Uploads/demo.csv ) 
[1] => Array ( [0] => token 
[1] => fe60313b0edfdfaf757f9744815454545) ) 

在php脚本中添加下面一行:

代码语言:javascript
运行
AI代码解释
复制
print_r($body); die();

function curl_setopt_custom_postfields($ch, $postfields, $headers = null);函数的末尾,我可以在浏览器上看到如下内容:

代码语言:javascript
运行
AI代码解释
复制
Array ( [0] => ------------------------------3c935d382987 
[1] => Content-Disposition: form-data; name="Files[]"; filename="demo.csv" 
[2] => Content-Type: application/octet-stream 
[3] => 
[4] => No,Name,Time,Verify,Mach,Ex,checktype,sid,code,Date 22364,22364,12/8/2017 10:28,Fingerpint,democollege-1-1,,I,1,0,12/8/2017 22365,22365,12/8/2017 9:29,Fingerpint,democollege-1-1,,I,1,0,12/8/2017 22366,22366,12/8/2017 10:59,Fingerpint,democollege-1-1,,I,1,0,12/8/2017 22369,22369,12/8/2017 11:58,Fingerpint,democollege-1-1,,I,1,0,12/8/2017 22364,22364,11/7/2017 10:28,Fingerpint,democollege-1-1,,I,1,0,11/7/2017 22365,22365,11/7/2017 9:29,Fingerpint,democollege-1-1,,I,1,0,11/7/2017 22366,22366,11/7/2018 10:59,Fingerpint,democollege-1-1,,I,1,0,11/7/2017 22369,22369,11/7/2018 11:58,Fingerpint,democollege-1-1,,I,1,0,11/7/2017 
[5] => ------------------------------3c935d382987 
[6] => Content-Disposition: form-data; name="token" 
[7] => 
[8] => fe60313b0edfdfaf757f9744815454545
[9] => ------------------------------3c935d382987-- 
[10] => ) 

费德勒:

EN

回答 2

Stack Overflow用户

发布于 2018-01-27 00:26:33

.Net网络应用程序文件;上载、下载、图像审查和SendCloud服务

Web.config

代码语言:javascript
运行
AI代码解释
复制
<appSettings>

 <!--FileService-->
    <add key="ftpUserName" value="fooUserName" />
    <add key="ftpPassword" value="fooPass" />

<!--FileController-->
    <add key="fileServiceLocalPath" value="~/App_Data/Upload" />
    <add key="fileServiceStoragePath" value="fooFtpAddress" />
    <add key="useCloud" value="false" />

</appSettings>

具有身份验证的文件控制器

代码语言:javascript
运行
AI代码解释
复制
[Authorize]
[RoutePrefix("api/File")]

 public class FileController : ApiController
    {
        IFileService fileService = null;
        public FileController(IFileService _fileService)
        {
            fileService = _fileService;
        }

        [Route("Upload"), HttpPost]
        public async Task<IHttpActionResult> Upload()
        {
            #region Condition

            if (!Request.Content.IsMimeMultipartContent())
                return Content(HttpStatusCode.UnsupportedMediaType, Messages.FUW0001);
            #endregion

            /// `localPath` and `useCloud` is get from Web.Config.
            string localPath = HostingEnvironment.MapPath(ConfigurationManager.AppSettings["fileServiceLocalPath"]);
            bool useCloud = Convert.ToBoolean(ConfigurationManager.AppSettings["useCloud"]);

            var provider = new MultipartFormDataStreamProvider(localPath);

            try
            {
                /// Loads the files into the local storage.
                await Request.Content.ReadAsMultipartAsync(provider);

                /// Check is exist valid file.
                if (provider.FileData.Count == 0)
                    return BadRequest(Messages.FUE0001 /*Message Type FUE001 = File Not Found */);

                IList<FileDto> modelList = new List<FileDto>();

                foreach (MultipartFileData file in provider.FileData)
                {
                    string originalName = file.Headers.ContentDisposition.FileName;
                    if (originalName.StartsWith("\"") && originalName.EndsWith("\""))
                    {
                        originalName = originalName.Trim('"');
                    }
                    if (originalName.Contains(@"/") || originalName.Contains(@"\"))
                    {
                        originalName = Path.GetFileName(originalName);
                    }

                    /// File information storage my database.
                    FileDto fileDto = new FileDto
                    {
                        OriginalName = Path.GetFileNameWithoutExtension(originalName),
                        StorageName = Path.GetFileName(file.LocalFileName),
                        Extension = Path.GetExtension(originalName).ToLower().Replace(".", ""),
                        Size = new FileInfo(file.LocalFileName).Length
                    };

                    modelList.Add(fileDto);
                }

                if (useCloud)
                    await fileService.SendCloud(modelList,localPath);

                await fileService.Add(modelList, IdentityClaimsValues.UserID<Guid>());

                return Ok(Messages.Ok);
            }
            catch (Exception exMessage)
            {
                return Content(HttpStatusCode.InternalServerError, exMessage);
            }
        }

    [   Route("Download"), HttpGet]
        public async Task<IHttpActionResult> Download(Guid id)
        {
            /// Get file information my database
            var model = await fileService.GetByID(id);

            if (model == null)
                return BadRequest();

            /// `localPath` is get from Web.Config.
            string localPath = HostingEnvironment.MapPath(ConfigurationManager.AppSettings["fileServiceLocalPath"]);

            string root = localPath + "\\" + model.StorageName;

            byte[] fileData = File.ReadAllBytes(root);
            var stream = new MemoryStream(fileData, 0, fileData.Length);

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(stream.ToArray())
            };

            response.Content.Headers.ContentDisposition =
                new ContentDispositionHeaderValue("attachment")
                {
                    FileName = model.OriginalName + "." + model.Extension,
                    Size=model.Size
                };

            response.Content.Headers.ContentType =
                new MediaTypeHeaderValue("application/octet-stream");

            IHttpActionResult result = ResponseMessage(response);
            return result;
        }

        [Route("ImageReview"), HttpGet]
        public async Task<IHttpActionResult> ImageReview(Guid id)
        {
            /// Get file information my database
            var model = await fileService.GetByID(id);

            if (model == null)
                return BadRequest();

            /// `localPath` is get from Web.Config.
            string localPath = HostingEnvironment.MapPath(ConfigurationManager.AppSettings["fileServiceLocalPath"]);

            string root = localPath + "\\" + model.StorageName;

            byte[] fileData = File.ReadAllBytes(root);
            var stream = new MemoryStream(fileData, 0, fileData.Length);

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream)
            };

            response.Content.Headers.ContentType =
                new MediaTypeHeaderValue("image/"+ model.Extension);

            IHttpActionResult result = ResponseMessage(response);

            return result;
        }
    }

档案服务

代码语言:javascript
运行
AI代码解释
复制
public interface IFileService
    {
        Task SendCloud(IList<FileDto> modelList, string localPath);
    }   

    public class FileService : IFileService
    {
        public Task SendCloud(IList<FileDto> modelList,string localPath)
        {
            /// `ftpUserName`, `ftpPassword` and `storagePath` is get from Web.Config.
            string ftpUserName = ConfigurationManager.AppSettings["ftpUserName"];
            string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"];
            string storagePath = ConfigurationManager.AppSettings["fileServiceStoragePath"];

            /// Uploaded files are sent to the cloud server.
            foreach (var model in modelList)
            {
                FtpWebRequest req = (FtpWebRequest)WebRequest.Create(storagePath + model.StorageName);

                req.UseBinary = true;
                req.Method = WebRequestMethods.Ftp.UploadFile;
                req.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
                byte[] fileData = File.ReadAllBytes(localPath + "\\" + model.StorageName);
                req.ContentLength = fileData.Length;

                Stream reqStream = req.GetRequestStream();
                reqStream.Write(fileData, 0, fileData.Length);
                reqStream.Close();
            }

            return Task.CompletedTask;
        }

    }

这是建筑的形象。

票数 6
EN

Stack Overflow用户

发布于 2018-01-28 18:25:30

我认为您的HttpClientMultipartFormDataContent方法应该可以工作。

只需注意输入名称,请尝试以下方法

代码语言:javascript
运行
AI代码解释
复制
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();

string filename = @"E:\Uploads\demo.csv"
    , filename2 = @"E:\Uploads\demo2.csv"
    , url = "http://demo.schooling.net/school/attendance"
    , token = "fe60313b0edfdfaf757f9744815454545"
    ;
byte[] bytes = System.IO.File.ReadAllBytes(filename);


// Keep `token` here, no quote escaping
form.Add(new StringContent(token), "token");

// Keep `Files[]` here
form.Add(new ByteArrayContent(bytes), "Files[]", Path.GetFileName(filename));

// To add 2nd file, keep the input name as `Files[]`
bytes = System.IO.File.ReadAllBytes(filename2);
form.Add(new ByteArrayContent(bytes), "Files[]", Path.GetFileName(filename2));        

var result = httpClient.PostAsync(url, form).Result;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48320322

复制
相关文章
ubuntu部署webserver
图片
懿曲折扇情
2022/08/24
3690
ubuntu部署webserver
Webserver推送技术
推送技术的基础思想是将浏览器主动查询信息改为server主动发送信息。server发送一批数据,浏览器显示这些数据,同一时候保证与server的连接。当server须要再次发送一批数据时,浏览器显示数据并保持连接。以后,server仍然能够发送批量数据,浏览器继续显示数据,依次类推。
全栈程序员站长
2022/07/12
4820
GoAhead WebServer移植
GoAhead  WebServer,它是一个源码免费、功能强大、可以运行在多个平台的嵌入式WebServer。
星哥玩云
2022/06/29
1.1K0
WebServer 是什么?
Web服务器是指驻留于因特网上某种类型计算机的程序。当Web浏览器(客户端)连到服务器上并请求文件时,服务器将处理该请求并将文件反馈到该浏览器上,附带的信息会告诉浏览器如何查看该文件(即文件类型)。服务器使用HTTP(超文本传输协议)与客户机浏览器进行信息交流,这就是人们常把它们称为HTTP服务器的原因。目前最主流的三个Web服务器是Apache Nginx IIS。
PM吃瓜
2019/08/13
1.3K0
WebServer 是什么?
CobaltStrike WebServer特征分析
在处理OPTIONS请求时候,更是uri都不看,直接返回200,并且在后面会加上Allow: OPTIONS,GET,HEAD,POST
谢公子
2022/06/09
1.3K0
CobaltStrike WebServer特征分析
CobaltStrike WebServer特征分析
在处理OPTIONS请求时候,更是uri都不看,直接返回200,并且在后面会加上Allow: OPTIONS,GET,HEAD,POST
JDArmy
2022/06/06
1.1K0
CobaltStrike WebServer特征分析
GoAhead WebServer移植小结
VxWorks中自带了WebServer组件,在network components->network protocols-> network applications下选择http server即可。也可以采用rapid control for Web。这里我们介绍GoAhead WebServer,它是一个源码免费、功能强大、可以运行在多个平台的嵌入式WebServer。
星哥玩云
2022/06/29
1.3K0
一个简单的WebServer,socke
一个简单的WebServer import socket import threading body = '<h1> web server </h1>' response_params = [ 'HTTP/1.0 200 OK', 'Content-Type: text/html;charset=utf-8', 'Content-Length: {}\r\n'.format(len(body.encode())), body, ] response = '\r\n'.j
py3study
2020/01/15
4010
Webserver ,Web container, Application server的区别
1)Webserver Web container Application server的区别:
马克java社区
2021/07/07
6040
嵌入式Linux系列第15篇:WebServer使用
Server一般有两种含义,一种是表示硬件,通常是指那些具有较高计算能力,能够提供给多个用户使用的计算机。另外一种含义是表示软件程序,这种程序主要用来对外提供某些服务,比如邮件服务、数据库服务、域名服务、网页服务等。
用户2366192
2021/05/31
2.1K0
网页防篡改专题3---WebServer方式
由于waf方式并没有解决网页篡改,只是缓解而已,特别是网页防篡改功能可能导致整个站点断服的风险,让waf方式差强人意。
血狼debugeeker
2019/08/01
1.3K0
写一个简单的webserver
基于 Python3 写的极简版 webserver。用于学习 HTTP协议,及 WEB服务器 工作原理。笔者对 WEB服务器 的工作原理理解的比较粗浅,仅是基于个人的理解来写的,存在很多不足和漏洞,目的在于给大家提供一个写 webserver 的思路。项目GitHub地址:https://github.com/hanrenguang/simple-webserver。
py3study
2020/01/03
6460
使用nodejs创建一个webServer
什么是 nodejs Node.js发布于2009年5月,由Ryan Dahl开发,是一个基于Chrome V8引擎的JavaScript运行环境,使用了一个事件驱动、非阻塞式I/O模型, 让JavaScript 运行在服务端的开发平台,它让JavaScript成为与PHP、Python、Perl、Ruby等服务端语言平起平坐的脚本语言。 Node.js对一些特殊用例进行优化,提供替代的API,使得V8在非浏览器环境下运行得更好,V8引擎执行Javascript的速度非常快,性能非常好,基于Chrome
是小张啊喂
2021/08/10
6160
使用nodejs创建一个webServer
什么是 nodejs Node.js发布于2009年5月,由Ryan Dahl开发,是一个基于Chrome V8引擎的JavaScript运行环境,使用了一个事件驱动、非阻塞式I/O模型, 让JavaScript 运行在服务端的开发平台,它让JavaScript成为与PHP、Python、Perl、Ruby等服务端语言平起平坐的脚本语言。 Node.js对一些特殊用例进行优化,提供替代的API,使得V8在非浏览器环境下运行得更好,V8引擎执行Javascript的速度非常快,性能非常好,基于Chrome J
是小张啊喂
2021/06/23
6120
Webserver管理系列:11、注意默认的隐含共享
我们能够通过取消”Microsoft网络的文件和打印机共享”服务来阻止别人訪问我们的共享文件:
全栈程序员站长
2022/07/13
3440
Webserver管理系列:11、注意默认的隐含共享
ASP.NET CORE Linux发布工具(文件对比 只上传差异文件;自动启停WebServer命令;上传完成自动预热WebServer)
最近这几日在搞一个小网站:教你啊 ;(感兴趣的朋友可以来捧场,在这个网站上有任何消费我都可以退还) 由于更新频繁,手动更新特别麻烦,于是开发了这个小工具 用了一段时间,还是挺顺手的,同时.NET Co
liulun
2018/05/28
9690
Arduino+w5100使用1:WebServer操作步骤所用硬件
操作步骤 1.将网络扩展板与UNO插接在一起,确保引脚连接正常。 pic1:uno+w5100 shield 2.如图所示连接UNO和PC机(PWR红灯长亮,AREF左侧绿灯长亮) pic2:conn
用户1733354
2018/05/22
2.9K0
SpringBoot内置源码解析WebServer初始化过程
在上一节中 Spring Boot 初始化了 WebServer 对应的工厂类。同时,我们也知道对应 Web容器的WebServer实现类有:TomcatWebServer、JettyWebServer和UndertowWebServer。
愿天堂没有BUG
2022/10/28
6310
SpringBoot内置源码解析WebServer初始化过程
【Rust每周一库】 http - Rust下简单的webserver库
本期的每周一库给大家带来的是一个rust下的webserver库,名字很直观就叫http。
MikeLoveRust
2020/02/20
1.4K0
让gulp-webserver自动化开发服务器支持SSI语法 (include等)
在gulpfile.js中加入上面的配置代码(核心是middleware那里的connectSSI配置),我们就可以使用.shtml文件格式的html了,从而在代码中可以使用ssi的语法实现一些本来需要后端支持的功能,如:include提取公共部分,避免前端coder们头疼的大量复制粘贴工作
fastmock
2022/07/13
4180

相似问题

WebServer + AP不工作?WebServer + STA

21

如何使用Corda-Spring-Webserver实现查询过滤?

13

NodeRED在NodeJS Webserver服务器上的实现

35

magento - webserver问题

50

多线程WebServer

12
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文