【问题标题】:Recieve/Accept file in WEBDAV from httpwebrequest POST or PUT in asp.net从 httpwebrequest POST 或 PUT 在 asp.net 中接收/接受 WEBDAV 文件
【发布时间】:2018-08-31 18:00:11
【问题描述】:

假设我在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”这样的 url,那么我会得到 405 错误方法未找到。

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

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

文件可以不接收直接上传到远程服务器吗 页面?

【问题讨论】:

    标签: asp.net file-upload httpwebrequest multipartform-data webdav


    【解决方案1】:

    这个问题是关于“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 方法,

    http://your.server.com/api/fileUpload

    fileUpload 是 api 控制器名称。

    如果你使用HTTP PUT 方法,那么

    i) 你想接收它以编程方式处理它。在 api 类中编写类似于 POST 方法的 PUT 方法。

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

    所以本例中的 URL 可以,

    "http://your.server.com/Imagefolder"
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多