>  기사  >  웹 프론트엔드  >  사진을 업로드하고 미리 보는 Ajax의 간단한 구현

사진을 업로드하고 미리 보는 Ajax의 간단한 구현

亚连
亚连원래의
2018-05-23 14:30:041543검색

이제 Ajax의 사진 업로드 및 미리보기의 간단한 구현을 소개하겠습니다. 이제 그것을 여러분과 공유하고 모든 사람에게 참고 자료로 제공하겠습니다.

1. 가장 간단한 Ajax 비동기 업로드 이미지로 직접 이동하여 미리보기

html:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图片上传 | cookie</title>
</head>
<body>
  file: <input type="file" id="images" name="image" /><br><br>
  desc: <input type="text" id="desc" name="desc" /><br><br>
  <input type="button" value="upload" onclick="upload();">
  
  <p class="images"></p>
  
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="js/upload.js"></script>
<script type="text/javascript">
  function upload() {
    $.ajaxFileUpload({
      url : &#39;upload.htm&#39;,
      fileElementId : &#39;images&#39;,
      dataType : &#39;json&#39;,
      data : {desc : $("#desc").val()},
      success : function(data) {
        var html = $(".images").html();
        html += &#39;<img width="100" height="100" src="/HotelManager/upload/&#39; + data.url + &#39;">&#39;
        $(".images").html(html);
      }
    })
    return false;
  }
</script>
</body>
</html>

servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    
    ServletFileUpload upload = new ServletFileUpload(factory);
    
    String path = request.getServletContext().getRealPath("/upload");
    String name = null;
    try {
      List<FileItem> items = upload.parseRequest(request);
      for (FileItem item : items) {
        if(item.isFormField()){
          System.out.println(item.getFieldName() + ": " + item.getString());
        } else {
          name = item.getName();
          item.write(new File(path,name));
        }
      }
      PrintWriter out = response.getWriter();
      out.print("{");
      out.print("url:\"" + name +"\"");
      out.print("}");
      
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

위 내용은 모두에게 도움이 되기를 바랍니다. 미래.

관련 기사:

ajax html 기반 파일 업로드 기술 요약

dom4j에서 XPath를 사용하는 간단한 예

Bootstrap의 DatePicker 날짜 범위 선택에 대한 간략한 토론

위 내용은 사진을 업로드하고 미리 보는 Ajax의 간단한 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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