从HttpWebRequest的POST收到/接受在WEBDAV文件或在asp.net PUT(Re

2019-10-29 07:16发布

假设我有这样的样本上传文件的方法POStFile.aspx 。 这种方法POST文件(上传文件)到http WEBDAV网址。

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;
        }
    }

从这里

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 :如果不是URL应该像"http://your.server.com/upload.aspx" ,而不是"http://your.server.com/upload"

如果我给的网址,如“ http://your.server.com/upload ”然后我得到找不到405错误的方法。

因此,它应该指向任何页面。

Question 2 :我应该如何接收后,将文件保存在upload.aspx。

该文件可以直接上传到远程服务器没有任何接收页面?

Answer 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.It完全取决于“如何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;
        }

所以,在URL页面POSTFile.aspx应指向API方法在这种情况下,

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

其中,文件上传是API控制器的名称。

如果您使用的HTTP PUT方法然后

i)您希望得到它的亲语法处理it.Write PUT类似于邮政API类方法的方法。

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

所以URL在这种情况下就可以了,

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

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

创建目标文件夹虚拟目录,一些其他的东西旁边。



文章来源: Recieve/Accept file in WEBDAV from httpwebrequest POST or PUT in asp.net