欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于jsp的AJAX多文件上传的实例

程序员文章站 2022-06-29 13:24:17
最近的项目开发中,遇到了一个多文件上传的问题,即在不刷新页面的情况下,上传多个文件至服务器。现总结分享如下: 本文主要采用了基于jsp的ajax,jquery,ser...

最近的项目开发中,遇到了一个多文件上传的问题,即在不刷新页面的情况下,上传多个文件至服务器。现总结分享如下:

本文主要采用了基于jsp的ajax,jquery,servlet等技术。

1.upload.jsp

点击上传时,调用对应的fileupload函数,通过ajax将文件异步传送到servlet中处理。注意在文件上载时,所使用的编码类型应当是“multipart/form-data”,它既可以发送文本数据,也支持二进制数据上载。

<%@ page language="java" contenttype="text/html; charset=utf-8" 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" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<base href="<%=basepath%>">
<title>insert title here</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
</head>
<script language="javascript" type="text/javascript">
  var buildph=0;
  var typeph=0;
  var planph=0;
  function fileupload1(){
    if($("#locationphoto").val()==""){
      alert("上传文件不能为空!");
      return false;
    }
    var file = $("#locationphoto").val();
    var pos=file.lastindexof("\\");
var filename=file.substring(pos+1);//获得文件名字
                                                                                                                               
    $.ajaxfileupload({
                                                                                                                                   
        url:"pictureservlet";,
        contenttype:"multipart/form-data; text/xml;charset=utf-8",
        secureuri:false,
        cache: false,//防止缓存
        fileelementid:'locationphoto',
        datatype: 'text/xml',
        success: function (data) {
          document.getelementbyid("locationspan").innerhtml = filename;
          alert(filename);
        },error: function (data, status, e){
          alert("fail");
        }
      }
    );
  }
  function fileupload2(){
    if($("#buildingphoto").val()==""){
      alert("上传文件不能为空!");
      return false;
    }
    var file = $("#buildingphoto").val();
    var pos=file.lastindexof("\\");
    var filename=file.substring(pos+1);
    buildph++;
    $.ajaxfileupload({
                                                                                                                                   
        url:"pictureservlet";,
        contenttype:"multipart/form-data; text/xml;charset=utf-8",
        secureuri:false,
        cache: false,//防止缓存
        fileelementid:'buildingphoto',
        datatype: 'text/xml',
        success: function (data) {
          document.getelementbyid("buildingspan"+buildph).innerhtml = filename;
          alert(filename);
        },error: function (data, status, e){
          alert("fail");
        }
      }
    );
  }
  function fileupload3(){
    if($("#typephoto").val()==""){
      alert("上传文件不能为空!");
      return false;
    }
    var file = $("#typephoto").val();
    var pos=file.lastindexof("\\");
    var filename=file.substring(pos+1);
    typeph++;
    $.ajaxfileupload({
                                                                                                                                   
        url:"pictureservlet";,
        contenttype:"multipart/form-data; text/xml;charset=utf-8",
        secureuri:false,
        cache: false,//防止缓存
        fileelementid:'typephoto',
        datatype: 'text/xml',
        success: function (data) {
          document.getelementbyid("typespan"+typeph).innerhtml = filename;
          alert(filename);
        },error: function (data, status, e){
          alert("fail");
        }
      }
    );
  }
</script>
<body>
<form id="form1" name="form1" method="post" action="">
 <table width="663" height="316" align="center">
  <tr>
   <td height="30" colspan="2">楼盘位置图:
    <span id="locationspan" ></span>
   <input type="file" name="locationphoto" id="locationphoto" value="this.val()"/>
   <input type="button" name="fileload1" id="fileload1" value="上传" onclick="fileupload1()"/>
   </td>
  </tr>
   <tr>
   <td height="30" colspan="2">楼盘照片:
   <span id="buildingspan1" ></span>
   <span id="buildingspan2" ></span>
   <span id="buildingspan3" ></span>
   <span id="buildingspan4" ></span>
   <input type="file" name="buildingphoto" id="buildingphoto" value="this.val()"/>
   <input type="button" name="fileload2" id="fileload2" value="上传" onclick="fileupload2()"/>
   </td>
  </tr>
    <tr>
   <td height="30" colspan="2">楼盘户型图:
    <span id="typespan1" ></span>
    <span id="typespan2" ></span>
    <span id="typespan3" ></span>
    <span id="typespan4" ></span>
   <input type="file" name="typephoto" id="typephoto" value="this.val()"/>
   <input type="button" name="fileload3" id="fileload3" value="上传" onclick="fileupload3()"/>
   </td>
  </tr>
 </table>
</form>
</body>
</html>

2.pictureservlet.java

通过该servlet接受jsp上传的数据流,存储到相应路径,并解析出文件名。

package com.servlet;
import java.io.bufferedoutputstream;
import java.io.dataoutputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.printwriter;
import javax.servlet.servletexception;
import javax.servlet.servletinputstream;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import com.realty.base.action.buildingaction;
/**
 * servlet implementation class pictureservlet
 */
@webservlet("/pictureservlet")
public class pictureservlet extends httpservlet {
  private static final long serialversionuid = 1l;
                                                    
  /**
   * @see httpservlet#httpservlet()
   */
  public pictureservlet() {
    super();
    // todo auto-generated constructor stub
  }
  /**
   * @see httpservlet#doget(httpservletrequest request, httpservletresponse response)
   */
  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    // todo auto-generated method stub
    dopost(request,response);
  }
  /**
   * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response)
   */
  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    // todo auto-generated method stub
     response.setcontenttype("text/xml");//是xml
      response.setheader("cache-control", "no-cache");
      response.setcharacterencoding("utf-8");
      string filepath ="e:/pic/";//文件上传的路径,实际开发中一般用相对路径
      string filename = "";
      string name="";
      servletinputstream in = request.getinputstream();
      byte[] buf = new byte[4048];
      int len = in.readline(buf, 0, buf.length);
      string f = new string(buf, 0, len - 1);
      while ((len = in.readline(buf, 0, buf.length)) != -1) {
        filename = new string(buf, 0, len,"utf-8");//解决汉字乱码问题
        int j = filename.lastindexof("\"");
        int s = filename.indexof("filename");
        name=filename.substring(s+10,j);
        filename = name;//通过上述处理可以得到上传的文件名
        system.out.println("filename="+filename);
                                                          
        dataoutputstream filestream = new dataoutputstream(new bufferedoutputstream(new fileoutputstream(filepath+ filename)));
        len = in.readline(buf, 0, buf.length);
        len = in.readline(buf, 0, buf.length);
        while ((len = in.readline(buf, 0, buf.length)) != -1) {
          string tempf = new string(buf, 0, len - 1);
          if (tempf.equals(f) || tempf.equals(f + "--")) {
            break;
          }
          else{
             filestream.write(buf, 0, len); // 写入
          }
        }
        filestream.close();
      }
      printwriter out=response.getwriter();
      string result = filename ;
      out.print(result);
      out.close();
      in.close();                       
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。