Thursday , 12 December 2024
HOT

How to post file to remote url

Bạn cần gửi file tới một URL xác đinh, url đó có thể nằm ngoài website (remote url) hoặc trong website của bạn. Ví dụ sau đây sẽ giúp bạn giải quyết vấn đề gửi file bằng cách sử dụng phương thức post (post method) trong asp.net

Code xử lý với file cần upload, file này sử dụng method post để gửi file tới remote server:


    public void UploadFile()
    {
        var nvc = new NameValueCollection();
        nvc.Add("user", userName);
        nvc.Add("password", password);
        nvc.Add("library", libraryName);

        HttpUploadFile(destinationUrl, uploadFile, "file", "image/png", nvc);
    }

    public void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
    {
        Response.Write(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");

        var wr = (HttpWebRequest)WebRequest.Create(url);
        wr.ContentType = "multipart/form-data; boundary=" + boundary;
        wr.Method = "POST";
        wr.KeepAlive = true;
        wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

        var 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);

        var 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();
            var stream2 = wresp.GetResponseStream();
            var reader2 = new StreamReader(stream2);
            Response.Write(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
        }
        catch (Exception ex)
        {
            Response.Write("Error uploading file: " + ex.Message);
            if (wresp != null)
            {
                wresp.Close();
                wresp = null;
            }
        }
        finally
        {
            wr = null;
        }
    }

Code xử lý với file cần download (remote server). Ở ví dụ này mình sử dụng file ashx, bạn có thể sử dụng file aspx cũng được:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;

namespace SitefinityWebApp.Widgets.Files
{
    public class UploadFileHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            //VALIDATE FILES IN REQUEST
            if (context.Request.Files.Count > 0)
            {
                try
                {
                    //HANDLE EACH FILE IN THE REQUEST
                    foreach (HttpPostedFile item in context.Request.Files)
                    {
                        item.SaveAs(context.Server.MapPath("~/Temp/" + item.FileName));
                        context.Response.Write("File uploaded");
                    }
                }
                catch (Exception ex)
                {
                    //NO FILES IN REQUEST TO HANDLE
                    context.Response.Write("Error: " + ex.Message);
                }
            }
            else
            {
                //NO FILES IN REQUEST TO HANDLE
                context.Response.Write("No file uploaded");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*