로컬 서버에서 파일을 다운로드하려고합니다. 파일을 다운로드하는 방법은 파일을 찾을 수없는 경우 오류 메시지를 표시합니다. JsonResult를 반환하는 메서드에서 파일을 다운로드 할 수 있습니까?
이
은 내보기에 코드입니다 :function download(id) {
var response = null;
var fileId = id == null? 0 : id;
var args = {fileId : fileId };
$.ajax({
type: 'POST',
url: '/Home/DownloadFile',
data: args,
dataType: "json",
traditional: true,
success: function (data) {
$("#message").attr('style', 'margin-left:auto; margin-right:auto; font- weight: bold; color: Red');
$("#message").html(data.message);
}
});
}
}
<div id="message"></div>
<a class="fileName" href="javascript:void(0)" onclick='download(@f.Id)'>@f.Name</a>
그리고 이것은 내 컨트롤러 :
public JsonResult DownloadFile(int fileId)
{
FileService fileService = new FileService();
DirectoryService directoryService = new DirectoryService();
File file = fileService.GetByFileId(fileId);
bool noError = false;
string _message = String.Empty;
if (file == null)
{
_message = "File does not exist";
}
else if (System.IO.File.Exists(file.FilePath))
{
using (StreamReader reader = System.IO.File.OpenText(file.FilePath))
{
Stream s = reader.BaseStream;
byte[] fileData = Utils.ReadStream(s);
string contentType = Utils.getContentType(file.FileName);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "attachment;filename=" + file.FileName);
Response.ContentType = contentType;
Response.BinaryWrite(fileData);
noError = true;
}
}
else
{
_message = "File \"" + file.FileName + "\" could not be found."; //File "foo.txt" could not be found
}
if (noError)
_message = String.Empty;
var data = new { message = _message };
return Json(data, JsonRequestBehavior.AllowGet);
}
이상한 것은 내가이 시험을 처음으로, 그것 일 것입니다. 아무것도 바꾸지 않았지만 지금은 메서드가 정상적으로 실행되지만 파일은 다운로드되지 않습니다. 누군가 제발 도와 줄 수 있니?
전달 된 ID가 맞습니까? 파일이 발견되었고 파일이 있습니까? – gideon
예. 디버거로 모든 것을 검사하고 있습니다. 내 생각 엔 아약스가 내 파일을 다운로드하지 못하도록 막아두고있다. –
이것은 사용해야하는 해결책이 아니지만 멈추고 다른 해결책이없는 경우 시도해 볼 수있다. 파일 다운로드 방법을 컨트롤러/동작으로 이동한다. (아내가 아님). 파일이 발견되면 파일 다운로드 작업으로 리디렉션을 보냅니다. 이 방법이 효과가 있을지 확실하지 않지만 이상적인 답변이 아니라고 확신합니다. – rkw