주석 : 아래에서는 HTML 5의 새로운 기능 파일 API를 사용하여 파일을 업로드하고 파일 업로드 진행률의 백분율을 표시합니다. 의도는 다음과 같습니다. 파일을 선택하면 현재 파일 정보가 표시됩니다.
여기서는 ASP.NET MVC를 서버로 결합하며 다른 서버 언어를 사용할 수도 있습니다. 이 스 니펫의 HTML을 살펴 보겠습니다.@using (html.beginform ( "업로드", "홈", formmethod.post, new {Enctype = "multipart/form-data",}))))
{
<div>
<label for = "file">
이미지 업로드 : </label>
<input type = "file"multure = "multiple"onchange = "FileSelected ();" />
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
<입력 유형 = "버튼"value = "업로드 이미지" />
</div>
<div>
</div>
}
관련 자바 스크립트는 다음과 같습니다.
함수 fileSelected () {
var file = document.getElementById ( 'filetouPload'). 파일 [0];
if (파일) {
var filesize = 0;
if (file.size> 1024 * 1024)
filesize = (math.round (file.size * 100 / (1024 * 1024)) / 100) .toString () + 'mb';
또 다른
filesize = (math.round (file.size * 100 / 1024) / 100) .toString () + 'kb';
document.getElementById ( 'filename'). innerhtml = 'name :' + file.name;
document.getElementById ( 'filesize'). innerHtml = 'size :' + filesize;
document.getElementById ( 'filetype'). innerHtml = 'type :' + file.type;
}
}
함수 uploadFile () {
var fd = new FormData ();
fd.append ( "filetoupload", document.getElementById ( 'filetouPload'). 파일 [0]);
var xhr = 새로운 xmlhttprequest ();
xhr.upload.addeventListener ( "Progress", UploadProgress, False);
xhr.addeventListener ( "로드", 업로드 컴퓨터, false);
xhr.addeventListener ( "error", uploadfailed, false);
xhr.addeventListener ( "Abort", uploadcanceled, false);
xhr.open ( "post", "home/upload");
xhr.send (fd);
}
함수 업로드 프로 로스 (EVT) {
if (evt.lengthcomputable) {
var % complete = math.round (evt.loaded * 100 /evt.total);
document.getElementById ( 'ProgressNumber'). innerHtml =%compplete.toString () + '%';
}
또 다른 {
document.getElementById ( 'ProgressNumber'). innerHtml = '계산할 수 없다';
}
}
기능 업로드 컴퓨터 (EVT) {
/ *이 이벤트는 서버가 응답을 다시 보낼 때 제기됩니다 */
Alert (evt.target.responsetext);
}
기능 업로드 플레어 (EVT) {
ALERT ( "파일을 업로드하려는 오류가있었습니다.");
}
함수 업로드 캔자 셀러 (EVT) {
ALERT ( "사용자가 업로드를 취소하거나 브라우저가 연결을 삭제했습니다.");
}
위의 것은 Onchange 이벤트에서 파일 선택된 함수를 실행하고 클릭 버튼에서 uploadfile 함수를 실행하는 기본 JavaScript입니다. 여기에서 xmlhttprequest를 사용하여 Ajax 업로드 파일을 구현하십시오. 코드는 Firefox 14에서 작동 할 수 있습니다. IE 9는 현재 파일 API를 지원하지 않으므로 여기에 참여할 수 있습니다. 서버 측 코드는 매우 간단합니다.
공개 클래스 홈 컨트롤러 : 컨트롤러
{
Public ActionResult Index ()
{
return view ();
}
/// <요약>
/// 지정된 파일을 업로드합니다.
/// </summary>
/// <param> 파일. </param>
/// <returns> actionResult </returns>
[httppost]
Public ActionResult 업로드 (httppostedfilebase [] filetoupload)
{
foreach (filetoupload의 httppostedfilebase 파일)
{
문자열 path = system.io.path.combine (Server.mappath ( "~/app_data"), system.io.path.getfilename (file.filename));
file.saveas (경로);
}
viewbag.message = "파일이 성공적으로 업로드 된 파일";
return retirecttoaction ( "index");
}
}
저자 : Petter Liu