>  기사  >  웹 프론트엔드  >  jquery 구현 ajaxfileupload 비동기 업로드 플러그인 튜토리얼

jquery 구현 ajaxfileupload 비동기 업로드 플러그인 튜토리얼

小云云
小云云원래의
2017-12-12 11:55:241321검색

이 글에서는 주로 jquery ajaxfileupload 비동기 업로드 플러그인에 대해 자세히 소개합니다. 관심 있는 친구들이 참고하면 도움이 될 것입니다.

서버는 struts2를 사용하여 파일 업로드를 처리합니다.

필요 환경:
jquery.js
ajaxfileupload.js
struts2가 의존하는 jar 패키지
및 struts2-json-plugin-2.1.8.1.jar

파일 업로드를 위한 작업 작성


package com.ajaxfile.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class FileAction extends ActionSupport {

  private File file;
  private String fileFileName;
  private String fileFileContentType;

  private String message = "你已成功上传文件";
  
  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public File getFile() {
    return file;
  }

  public void setFile(File file) {
    this.file = file;
  }

  public String getFileFileName() {
    return fileFileName;
  }

  public void setFileFileName(String fileFileName) {
    this.fileFileName = fileFileName;
  }

  public String getFileFileContentType() {
    return fileFileContentType;
  }

  public void setFileFileContentType(String fileFileContentType) {
    this.fileFileContentType = fileFileContentType;
  }

  @SuppressWarnings("deprecation")
  @Override
  public String execute() throws Exception {
    
    String path = ServletActionContext.getRequest().getRealPath("/upload");

    try {
      File f = this.getFile();
      if(this.getFileFileName().endsWith(".exe")){
        message="对不起,你上传的文件格式不允许!!!";
        return ERROR;
      }
      FileInputStream inputStream = new FileInputStream(f);
      FileOutputStream outputStream = new FileOutputStream(path + "/"+ this.getFileFileName());
      byte[] buf = new byte[1024];
      int length = 0;
      while ((length = inputStream.read(buf)) != -1) {
        outputStream.write(buf, 0, length);
      }
      inputStream.close();
      outputStream.flush();
    } catch (Exception e) {
      e.printStackTrace();
      message = "对不起,文件上传失败了!!!!";
    }
    return SUCCESS;
  }

}


struts.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
  <package name="struts2" extends="json-default">
    <action name="fileUploadAction" class="com.ajaxfile.action.FileAction">
      <result type="json" name="success">
        <param name="contentType">
          text/html
        </param>
      </result>
      <result type="json" name="error">
        <param name="contentType">
          text/html
        </param>
      </result>
    </action>
  </package>
</struts>


Action과 결합된 struts.xml의 결과 구성에 주의하세요.

contentType 매개변수가 있어야 합니다. 그렇지 않으면 브라우저는 항상 반환된 JSON 결과를 파일로 저장하라는 메시지를 표시하고 처리를 위해 ajaxfileupload에 전달하지 않습니다. 이는 struts2 JSON 플러그인의 기본 contentType이 application/json인 반면 ajaxfileupload에는 text/html이 필요하기 때문입니다.

파일 업로드를 위한 JSP 페이지


<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/ajaxfileupload.js"></script>
    <script type="text/javascript">
  function ajaxFileUpload()
  {
    
    $("#loading")
    .ajaxStart(function(){
      $(this).show();
    })//开始上传文件时显示一个图片
    .ajaxComplete(function(){
      $(this).hide();
    });//文件上传完成将图片隐藏起来
    
    $.ajaxFileUpload
    (
      {
        url:&#39;fileUploadAction.action&#39;,//用于文件上传的服务器端请求地址
        secureuri:false,//一般设置为false
        fileElementId:&#39;file&#39;,//文件上传空间的id属性 <input type="file" id="file" name="file" />
        dataType: &#39;json&#39;,//返回值类型 一般设置为json
        success: function (data, status) //服务器成功响应处理函数
        {
          alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中action中定义的成员变量
          
          if(typeof(data.error) != &#39;undefined&#39;)
          {
            if(data.error != &#39;&#39;)
            {
              alert(data.error);
            }else
            {
              alert(data.message);
            }
          }
        },
        error: function (data, status, e)//服务器响应失败处理函数
        {
          alert(e);
        }
      }
    )
    
    return false;

  }
  </script>
  </head>
  <body>
    <img src="loading.gif" id="loading" style="display: none;">
    <input type="file" id="file" name="file" />
    <br />
    <input type="button" value="上传" onclick="return ajaxFileUpload();">
  </body>
</html>


6c04bd5ca3fcae76e30b72ad730ca86d에 있는 코드에 주의하세요. 형식이 없습니다. ajaxFileUpload() 메서드는 버튼을 클릭할 때만 트리거됩니다. 주목해야 할 것은 js 파일이 도입되는 순서입니다. ajaxfileupload.js는 jquery에 따라 다릅니다.

관련 권장 사항:

jquery는 로그인 세부 정보 및 예제 코드 입력을 구현합니다.

Jquery는 양식 확인을 구현하며 모든 확인은 제출 전에 통과해야 합니다

php+jquery는 검색 프롬프트 기능 예제를 구현합니다

위 내용은 jquery 구현 ajaxfileupload 비동기 업로드 플러그인 튜토리얼의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.