asp.net mvc의 jQuery ajax 업로드 파일
내보기에 파일이 있습니다.
<form id="upload" enctype="multipart/form-data">
<input type="file" name="fileUpload" id="fileUpload" size="23" />
</form>
및 ajax 요청
$.ajax({
url: '<%=Url.Action("JsonSave","Survey") %>',
dataType: 'json',
processData: false,
contentType: "multipart/mixed",
data: {
Id: selectedRow.Id,
Value: 'some date was added by the user here :))'
},
cache: false,
success: function (data) {}
});
그러나 Request.Files에 파일이 없습니다 . ajax 요청에 어떤 문제가 있습니까?
ASP.Net MVC에서 AJAX를 사용하여 파일 업로드
HTML5 이후 변경된 사항
자바 펼쳐
document.getElementById('uploader').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
}
제어 장치
public JsonResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i]; //Uploaded file
//Use the following properties to get file's name, size and MIMEType
int fileSize = file.ContentLength;
string fileName = file.FileName;
string mimeType = file.ContentType;
System.IO.Stream fileContent = file.InputStream;
//To save file, use SaveAs method
file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
}
return Json("Uploaded " + Request.Files.Count + " files");
}
편집 : HTML
<form id="uploader">
<input id="fileInput" type="file" multiple>
<input type="submit" value="Upload file" />
</form>
AJAX 파일 업로드는 이제 요청 속성에 FormData
개체를 전달하여 가능합니다 .data
$.ajax
OP가 특히 jQuery 구현을 구매하고 여기에 있습니다.
<form id="upload" enctype="multipart/form-data" action="@Url.Action("JsonSave", "Survey")" method="POST">
<input type="file" name="fileUpload" id="fileUpload" size="23" /><br />
<button>Upload!</button>
</form>
$('#upload').submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
},
error: function(xhr, error, status) {
console.log(error, status);
}
});
});
public JsonResult Survey()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
// save file as required here...
}
return Json(new { UploadedFileCount = Request.Files.Count });
}
MDN의 FormData에 대한 추가 정보
ajax를 통해 파일을 업로드 할 수 있습니다. 전체 포스트 백을 수행하는 것이 좋습니다. iFrame 또는 기타 트릭을 많이 사용합니다. 이는 주로 보안 문제 때문입니다.
다음 은 Steve Sanderson의 SWFUpload 및 ASP.Net MVC를 사용 하는 샘플 프로젝트 를 포함한 적절한 글 입니다. Asp.Net MVC (당시 MVC를 처음 사용 했었 음)에서 제대로 작동하는 것을 읽은 첫 번째 글입니다. 도움이 되었기를 바랍니다.
ajax를 사용하여 양식을 게시하는 경우 $ .ajax 메소드를 사용하여 이미지를 보낼 수 없으며 이미지를 저장하기 위해 고전적인 xmlHttpobject 메소드를 사용해야하며 다른 대안은 버튼 대신 제출 유형을 사용합니다.
vuejs 버전 : v2.5.2에 다음과 같은 샘플이 있습니다.
<form action="url" method="post" enctype="multipart/form-data">
<div class="col-md-6">
<input type="file" class="image_0" name="FilesFront" ref="FilesFront" />
</div>
<div class="col-md-6">
<input type="file" class="image_1" name="FilesBack" ref="FilesBack" />
</div>
</form>
<script>
Vue.component('v-bl-document', {
template: '#document-item-template',
props: ['doc'],
data: function () {
return {
document: this.doc
};
},
methods: {
submit: function () {
event.preventDefault();
var data = new FormData();
var _doc = this.document;
Object.keys(_doc).forEach(function (key) {
data.append(key, _doc[key]);
});
var _refs = this.$refs;
Object.keys(_refs).forEach(function (key) {
data.append(key, _refs[key].files[0]);
});
debugger;
$.ajax({
type: "POST",
data: data,
url: url,
cache: false,
contentType: false,
processData: false,
success: function (result) {
//do something
},
});
}
}
});
</script>
참고 URL : https://stackoverflow.com/questions/2428296/jquery-ajax-upload-file-in-asp-net-mvc
'ProgramingTip' 카테고리의 다른 글
Express에서 app.use ()와 router.use ()의 차이점 (0) | 2020.11.07 |
---|---|
하이라이트 색상 변경 (0) | 2020.11.07 |
새 창에서 Vim에서 새 파일을 여는 방법 (0) | 2020.11.06 |
Pandas : DataFrame 샘플링 (0) | 2020.11.06 |
Content-Range와 Range 헤더의 차이점은 무엇입니까? (0) | 2020.11.06 |