我正在使用ASP.NET MVC调用REST API下载文件(任何类型(。我不确定如何直接在浏览器中显示该文件。
该文件可能是任何格式PDF/image/excel/word/etc。
这是我来自JQuery,Controller和Rest API调用的代码。
请帮助我如何从REST API->控制器 -> jQuery?
中发送回文件数据jQuery ajax调用。这是表上的onclick事件
//JQuery Ajax call to 'GetDocument'
$("#DivAttachmentDetails td ").click(function () {
var DocumentumId = $('#hdnDocumentumId').val();
$.ajax({
type: 'POST',
url: getExactPath('/Supplier/GetDocument'),
data: {
documetObj: DocumentumId
},
dataType: 'json',
async: false,
success: function (jsonData) {
//alert('Hello');
},
error: function () {
alert("Unable to fetch the Document.");
}
});
});
控制器方法从jQuery:
//Method in the Controller called from jQuery Ajax.
public JsonResult GetDocument(string documetObj)
{
DocumentumUtil dUtil = new DocumentumUtil();
String dId;String fileName;String fileExt;String doc = "";
String applicationType = "";
String[] docum;
docum = documetObj.Split(':');
dId = docum[0];
fileName = docum[1].Substring(0, docum[1].LastIndexOf('.'));
fileExt = docum[2];
try
{
String contenType = dUtil.getFileContentType(dId); // Fetch the file content type based on DocumentumId
doc = dUtil.getDocument(dId, fileName, contenType);
}
catch(System.Exception ex) {}
return this.Json("", JsonRequestBehavior.AllowGet);
}
此REST API调用:
// This is the method i am calling from Controller -GetDocument()
public String getDocument(String documentId, String fileName, String contenType)
{
_httpClient = new HttpClient();
D2Document newDocument = new D2Document();
newDocument.SetPropertyValue("object_name", fileName);
newDocument.SetPropertyValue("a_content_type", contenType);
String documentURL = ConfigurationManager.AppSettings["DOCUMENTUM_URL"] + "objects/"+ documentId + "/content-media?format=" + contenType + "&modifier=&page=0";
JSON_GENERIC_MEDIA_TYPE = new MediaTypeWithQualityHeaderValue("application/json");
JSON_VND_MEDIA_TYPE = new MediaTypeWithQualityHeaderValue("application/vnd.emc.documentum+json");
try
{
using (var multiPartStream = new MultipartFormDataContent())
{
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password)));
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
using (HttpResponseMessage response = _httpClient.GetAsync(documentURL).Result)
{
if (response != null)
{
var responsestream = response.Content;
}
}
}
}
}
如何将内容转换为流/字节?
这是我已转换为文件流的代码。
using (HttpResponseMessage response = _httpClient.GetAsync(documentURL).Result)
{
if (response != null)
{
HttpContent content = response.Content;
//Get the actual content stream
Stream contentStream = content.ReadAsStreamAsyn().Result;
//copy the stream to File Stream. "file" is the variable have the physical path location.
contentStream.CopyTo(file);
}
}