저는 asp.net mvc를 사용하여 개발하는 초보자입니다. 나는 파일을 다운로드하기 위해 노력하고있어 (이미지, PDF를 ...) 다음은 ASP 컨트롤러angularJS 및 asp.net mvc를 사용하여 파일 다운로드
[HttpPost]
public HttpResponseMessage Download(int id)
{
var db = new TutorialGEDEntities();
Tutorial fileToDownload = db.Tutorials.Find(id);
string name = fileToDownload.filepath;
Debug.WriteLine("filepath " + name);
try
{
if (!string.IsNullOrEmpty(name))
{
//var root = System.Web.HttpContext.Current.Server.MapPath(name);
var filePath = System.Web.HttpContext.Current.Server.MapPath(name); ;
char[] s = new char[name.Length - name.LastIndexOf("\\") - 1];
name.CopyTo(name.LastIndexOf("\\")+1, s, 0, name.Length - name.LastIndexOf("\\")-1);
String fileName = new String(s);
using (MemoryStream ms = new MemoryStream())
{
using (FileStream file = new FileStream(name, FileMode.Open, FileAccess.Read))
{
Debug.WriteLine("file " + file.Length);
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
ByteArrayContent content = new ByteArrayContent(bytes.ToArray());
httpResponseMessage.Content = content;
httpResponseMessage.Content.Headers.Add("x-filename", fileName);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
}
}
}
return null;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Data);
return null;
}
}
과 문제는 내가 할 수있는 각 컨트롤러
$http({
method: 'POST',
url: 'Download',
data: { 'name': file.filepath },
responseType: 'arraybuffer'
}).success(function (content, status, headers) {
headers = headers();
console.log(content);
console.log(status)
var filename = headers['x-filename'];
var contentType = headers['content-type'];
var linkElement = document.createElement('a');
try {
var blob = new Blob([content], { type: contentType });
console.log(blob);
var url = URL.createObjectURL(blob);
console.log(url)
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", filename);
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
} catch (ex) {
console.log(ex);
}
}).error(function (data) {
console.log(data);
});
};
에 내 코드
입니다 정의되지 않은 파일과 빈 파일. 내가 잘 작동하는 코드를 디버깅, ASP 컨트롤러에서 데이터를 잘 int HttpResponse 구조입니다.
어떻게 작동시킬 수 있습니까? 다운로드 기능을 받으려면 다른 제안을 환영합니다.
편집 :
는 내가 asp.net 컨트롤러에서 다운로드 연료 소모량을 변경했습니다. 나는 HttpResponseMessage 클래스를 사용했다. 이 솔루션에서는 Response 클래스를 사용했다.
ASP를 컨트롤러
는 지금 :[HttpPost]
public void Download(String name)
{
Debug.WriteLine("filepath " + name);
if (!string.IsNullOrEmpty(name))
{
char[] s = new char[name.Length - name.LastIndexOf("\\") - 1];
name.CopyTo(name.LastIndexOf("\\")+1, s, 0, name.Length - name.LastIndexOf("\\")-1);
String fileName = new String(s);
//var filePath = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/") + fileName;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", fileName);
Response.AppendHeader("X-FileName", fileName);
Response.TransmitFile(name);
Response.End();
}
}
은 '개체 = 새로운 된 MouseEvent는 ("클릭", { "보기"창, "거품"사실 "취소 할"거짓 })이 var에 clickEvent에이 작업을 지원 절하지 않는다; – Exzile