从httpwebrequest POST或asp.net中的PUT接收/接受WEBDAV中的文件

问题描述 投票:0回答:1

假设我在POStFile.aspx中有这样的示例上传文件方法。这个方法POST文件(上传文件)到http WEBDAV url。

public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc) {
        log.Debug(string.Format("Uploading {0} to {1}", file, url));
        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.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);
            log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
        } catch(Exception ex) {
            log.Error("Error uploading file", ex);
            if(wresp != null) {
                wresp.Close();
                wresp = null;
            }
        } finally {
            wr = null;
        }
    }

From here

NameValueCollection nvc = new NameValueCollection();
    nvc.Add("id", "TTR");
    nvc.Add("btn-submit-photo", "Upload");
    HttpUploadFile("http://your.server.com/upload", 
         @"C:\test\test.jpg", "file", "image/jpeg", nvc);

Question 1:网址不应该像"http://your.server.com/upload.aspx"而不是"http://your.server.com/upload"

如果我给网址像“http://your.server.com/upload”那么我得到405错误方法没有找到。

所以它应该指向任何页面。

Question 2:我应该如何收到帖子并将文件保存在upload.aspx中。

文件可以直接上传到远程服务器而无需任何接收页面吗?

asp.net file-upload httpwebrequest multipartform-data webdav
1个回答
0
投票

这个问题是关于“File transfer to WEBDAV http URL using or POST or PUT method

以上是POST method的样本。类似地,PUT method可以与POST方法略有不同。

Question 1 : Shouldn't the url should be like "http://your.server.com/upload.aspx" instead of "http://your.server.com/upload"

对于像我这样的新手,主要的困惑是URL。它完全依赖于“WEBDAV服务器如何接收POST或PUT方法?”

我认为对于POST方法,应该有一个接收页面接受来自POSTfile页面的文件和其他参数,并将文件保存到磁盘。

我不知道.net代码,但WEB API具有内置功能,可以解析像"multipart/form-data; boundary=---------------------------8d60ff73d4553cc"这样的数据

下面的代码只是示例代码,

[HttpPost]
        public async Task<FileUploadDetails> Post()
        {
            // file path
            var fileuploadPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");

            //// 
            var multiFormDataStreamProvider = new MultiFileUploadProvider(fileuploadPath);

            // Read the MIME multipart asynchronously 
            await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);

            string uploadingFileName = multiFormDataStreamProvider
                .FileData.Select(x => x.LocalFileName).FirstOrDefault();

            // Files
            //
            foreach (MultipartFileData file in multiFormDataStreamProvider.FileData)
            {
                Debug.WriteLine(file.Headers.ContentDisposition.FileName);
                Debug.WriteLine("File path: " + file.LocalFileName);
            }

            // Form data
            //
            foreach (var key in multiFormDataStreamProvider.FormData.AllKeys)
            {
                foreach (var val in multiFormDataStreamProvider.FormData.GetValues(key))
                {
                    Debug.WriteLine(string.Format("{0}: {1}", key, val));
                }
            }
             //Create response
            return new FileUploadDetails
            {

                FilePath = uploadingFileName,

                FileName = Path.GetFileName(uploadingFileName),

                FileLength = new FileInfo(uploadingFileName).Length,

                FileCreatedTime = DateTime.Now.ToLongDateString()
            };
            return null;
        }

所以POSTFile.aspx页面中的url应该指向这种情况下的API方法,

“Qazxswpoi”

其中fileUpload是api控制器名称。

如果你正在使用http://your.server.com/api/fileUpload方法

i)你想以专业的方式处理它。在api类中写入类似于POST方法的PUT方法。

ii)您想使用PUT方法直接将文件保存到文件夹。

所以在这种情况下URL可以是,

HTTP PUT

是的,这可以通过额外的IIS设置来完成。

在Tar​​get文件夹中创建虚拟目录,除了其他一些东西。

© www.soinside.com 2019 - 2024. All rights reserved.