servlet+ajaxjquery 上传图片

html

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://"
   + request.getServerName() + ":" + request.getServerPort()
   + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script language="javascript" src="<%=basePath%>js/jquery.js" ></script>
 <script language="javascript" src="<%=basePath%>js/ajaxfileupload.js" > </script>
 <script language="javascript" type="text/javascript" src="<%=basePath%>js/ezeditor.js"></script>
 <script type="text/javascript">
 function ajaxFileUpload()
 {
 
 $("#loading")
        .ajaxStart(function(){
            $(this).show();
        })//开始上传文件时显示一个图片
        .ajaxComplete(function(){
            $(this).hide();
        });//文件上传完成将图片隐藏起来
       
       $.ajaxFileUpload({
                
url:'<%=basePath %>FileUpload',             //需要链接到服务器地址
                 secureuri:false,
                 fileElementId:'uploadFileInput',                         //文件选择框的id属性
                 dataType: 'json',                                     //服务器返回的格式,可以是json
                 success: function (data, status)             //相当于java中try语句块的用法
                 {  
                 //alert(data);       //data是从服务器返回来的值  
                     $('#result').html('上传图片成功!请复制图片地址<br/>'+data.src);
 
                 },
                 error: function (data, status, e)             //相当于java中catch语句块的用法
                 {
                     $('#result').html('上传图片失败');
                 }
               }
             );
    }
 </script>
  </head>
 
  <body>
  <div id="result" style="FONT:12px 宋体"></div><br/>
 <img id="loading" src="loading.gif" style="display:none;">
  <form name="form_uploadImg" action="" method="POST" enctype="multipart/form-data">
 <input id="uploadFileInput" type="file" size="45" name="uploadFileInput" class="input" />
 <input type="button" id="buttonUpload" onclick="return ajaxFileUpload();" value="上传图片"/>
 </form>
</html>

 

 

Servlet

 

package com.lz.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

public class FileUpload extends HttpServlet {

 public FileUpload() {
  super();
 }

 public void destroy() {
  super.destroy();
 }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  response.setContentType("text/html");  
  response.setCharacterEncoding("UTF-8");
  String realDir = request.getSession().getServletContext().getRealPath("");
  String contextpath = request.getContextPath();
  String basePath = request.getScheme() + "://"
  + request.getServerName() + ":" + request.getServerPort()
  + contextpath + "/";

  try {
  String filePath = "uploadfiles";
  String realPath = realDir+"
\\"+filePath;
  //判断路径是否存在,不存在则创建
  File dir = new File(realPath);
  if(!dir.isDirectory())
      dir.mkdir();

  if(ServletFileUpload.isMultipartContent(request)){

      DiskFileItemFactory dff = new DiskFileItemFactory();
      dff.setRepository(dir);
      dff.setSizeThreshold(1024000);
      ServletFileUpload sfu = new ServletFileUpload(dff);
      FileItemIterator fii = null;
      fii = sfu.getItemIterator(request);
      String title = "";   //图片标题
      String url = "";    //图片地址
      String fileName = "";
   String state="SUCCESS";
   String realFileName="";
      while(fii.hasNext()){
          FileItemStream fis = fii.next();

          try{
              if(!fis.isFormField() && fis.getName().length()>0){
                  fileName = fis.getName();
      Pattern reg=Pattern.compile("[.]jpg|png|jpeg|gif$");
      Matcher matcher=reg.matcher(fileName);
      if(!matcher.find()) {
       state = "文件类型不允许!";
       break;
      }
      realFileName = new Date().getTime()+fileName.substring(fileName.lastIndexOf("."),fileName.length());
                  url = realPath+"
\\"+realFileName;

                  BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流
                  FileOutputStream a = new FileOutputStream(new File(url));
                  BufferedOutputStream output = new BufferedOutputStream(a);
                  Streams.copy(in, output, true);//开始把文件写到你指定的上传文件夹
              }else{
                  String fname = fis.getFieldName();

                  if(fname.indexOf("pictitle")!=-1){
                      BufferedInputStream in = new BufferedInputStream(fis.openStream());
                      byte c [] = new byte[10];
                      int n = 0;
                      while((n=in.read(c))!=-1){
                          title = new String(c,0,n);
                          break;
                      }
                  }
              }

          }catch(Exception e){
              e.printStackTrace();
          }
      }
      response.setStatus(200);
      String retxt ="{src:'"+basePath+filePath+"/"+realFileName+"',name:'123'}";
      response.getWriter().print(retxt);
  }
  }catch(Exception ee) {
   ee.printStackTrace();
  }
  
 }
 public void init() throws ServletException {
  // Put your code here
 }

}

需要  jquery.js, ajaxfileupload.js  jar包

 

 

阅读更多
个人分类: 上传
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭