1. 檔案只能放在 Firewall 內的後台用 Web server (Server A).
2. 使用者只能存取 DMZ 的 Web server (Server B).
3. Server B 只能用 HTTP 通過 Firewall 向 Server A 要資料.(i.e. Server B 不能掛戴 Server A 的目錄成為虛擬目錄)
所以在 Server B 上面建立了一支程式用 HTTP 的方式讀取 Server A 的檔案再寫出去.
例如, http://ServerB/Upload/test.pdf 會讀取 http://ServerA/Upload/test.pdf 再送到 Client 端
namespace WWW.Controllers
{
public class UploadController : Controller
{
// GET: Upload
public void Index(string Filename)
{
//Create a stream for the file
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
string url = "http://admin-dev.nanya.bike.idv.tw/newnanyaback/Upload/" + Filename;
// The number of bytes read
try
{
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Response;
if (Filename.ToLower().EndsWith(".png") ||
Filename.ToLower().EndsWith(".jpg") ||
Filename.ToLower().EndsWith(".jpeg") ||
Filename.ToLower().EndsWith(".gif")
)
{
resp.ContentType = "image";
}
else
{
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlEncode(Filename, Encoding.UTF8) + "\"");
}
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
}
}
}
但不是這樣就好了, 在 RouteConfig.cs 中要加上:
routes.MapRoute(
name: "Upload",
url: "Upload/{filename}",
defaults: new { controller = "Upload", action = "Index", filename = UrlParameter.Optional }
);
此外在 Web.Config 中也要加上:
<system.webServer>
<handlers>
<add name="UrlRoutingHandler_Upload"
type="System.Web.Routing.UrlRoutingHandler,
System.Web, Version=4.0.0.0,
Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
path="/Upload/*"
verb="GET"/>
</handlers>
</system.webServer>
參考:
http://stackoverflow.com/questions/5596747/download-stream-file-from-url-asp-net
http://blog.darkthread.net/post-2014-12-05-mvc-routing-for-url-with-filename.aspx