1

Hi i want to do file upload using ajax and Apache Commons File Upload. In Servlet i have:

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
System.out.println(response.getCharacterEncoding());
response.setCharacterEncoding("UTF-8");
System.out.println(response.getCharacterEncoding());
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("wtpwebapps<br/>");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
    writer.println("<HTML>");
        writer.println("<HEAD <TITLE> Upload4 </TITLE> </HEAD>");
        writer.println("<BODY>");
        writer.println("<FORM action = \"Upload_Servlet\" method = \"post\" enctype = \"multipart/form-data\">");
        writer.println("<INPUT type = file name = ufile>");
        writer.println("<INPUT type = submit value = \"Attach\">");
        writer.println("<h1>its not multipart</h1>");
        writer.println("</FORM>");
        writer.println("</BODY>");
        writer.println("</HTML>");
        return;
    }          
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> list=null;
String mifpath= "1";
String path = " ";
String mif = " ";
String from = "\\\\";
String to ="/";
String error="";
 try{
  list = upload.parseRequest(request);
  Iterator<FileItem> it = list.iterator();
  response.setContentType("text/html");
  while ( it.hasNext() ) 
  {

    FileItem item = (FileItem) it.next();
    File disk = new File("C:/uploaded_files/"+item.getName());

        path = disk.toString();

        String code = new String(path.substring(path.lastIndexOf("."), path.length()).getBytes("ISO-8859-1"),"utf-8");
        if (code.equalsIgnoreCase(".zip"))
        {
            mifpath=path;
            mif = mifpath.replaceAll(from, to);
            item.write(disk);
            error=unzip.unpack(mif, "C:/uploaded_files");
        }
        else
        {
            error = "Выбранный файл не является архивом zip";

        }
  }
}
 catch ( Exception e ) {
  log( "Upload Error" , e);
}
 request.setAttribute("error", error);
 request.getRequestDispatcher("/Home.jsp").forward(request, response);

// String redictedURL="http://localhost:8080/redicted_test/Home.jsp";
// response.sendRedirect(redictedURL);
writer.close();
}
}

But i dont know what to do in client side.

Try to use ajaxfileupload library, but nothint heppens.

jsp

<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.SQLException"%>
<%@ page import="java.sql.Statement"%>
<%@ page import="java.sql.ResultSet"%>


<%@ 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>OpenLayers map preview</title>
<link href="http://localhost:8080/geoserver/openlayers/theme/default/style.css"      type="text/css"/>
<link href="fileuploader.css" type="text/css"/>
<script src="jquery.min.js"></script>
<script src="ajaxfileupload.js"></script>
<script src="fileuploader.js"></script>

<style type="text/css"> 
    /*<![CDATA[*/
        div.container {
            width: 100%;
            float: left;
            margin-right: -270px;
            }
        div.content {
            margin-right: 270px;
            }       
        div.info{   
                width: 270px;
                float: right;
                }
        div.clearing {
            height: 0;
            clear: both;
            }
        div.list {background-color:#dddddd; border-right:2px dashed #717dc9; width:250px; float:right; margin-left:10px;height:400}
        div.upload{background-color:#dddddd; height:190px; width:252px; float: right; margin-top:10px }
        div.listtitle {margin-left:10px; background-color:#dddddd}
        div.check {width:50%;float: left}
        div.filelist {overflow: auto; height:310px; margin-left:10px}
        div.upload_int{
        margin-left:10px
        }
        /* General settings */
            body {
                font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-size: small;
                sans-serif; width:700px; margin:100px auto;
                }
        /* The map and the location bar */
            #map {
                clear: both;
                position: relative;
                max-width: 1000px;
                min-width: 100px;
                height: 590px;
                border: 1px solid black;
                }
    /*]]>*/
    </style>
<!-- Import OpenLayers, reduced, wms read only version -->
<script src="Scripts/OpenLayers/OpenLayers.js" type="text/javascript">
</script>
<script defer="defer" type="text/javascript">
var map;
var ch=[];
var tiled;

function init(){
var bounds = new OpenLayers.Bounds(6359825.735024724,6796708.483322172,9197952.978460854,10728325.920322442);
var options = {
    controls: [],
    maxExtent: bounds,
    maxResolution: 156543.0399,
    projection: "EPSG:900913",
    units: 'm'
};
map = new OpenLayers.Map('map', options);

    var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
    var toProjection   = new OpenLayers.Projection("EPSG:900913");

// setup tiled layer



    osm = new OpenLayers.Layer.OSM( "OpenStreet Maps");

    map.addLayers([osm]);

// build up all controls
map.addControl(new OpenLayers.Control.PanZoomBar({
    position: new OpenLayers.Pixel(2, 15)
}));
map.addControl(new OpenLayers.Control.Navigation());
map.addControl(new OpenLayers.Control.Scale($('scale')));
    map.addControl( new OpenLayers.Control.LayerSwitcher() );
map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));
map.zoomToExtent(bounds);

        //---------------
        document.getElementById("check").onclick=function(){
        var count = 0;

        var inputs = document.getElementsByTagName('input');
        for (var j = 0; j < inputs.length; j++){
            if (inputs[j].type == 'checkbox')
            {
                count++;

            }
        }

        id=[];
        var doc;
        var i=0;

        //var params;
        var obj_id=" ";
        var or ="or";
        var fin_obj="";
        var filter="";
        var div = document.getElementById("list");
        elements = getElementsByClass('myclass', div);
        var b;
        for(b=0;b<elements.length;b++)
        {
            if(elements[b].checked)
            {id.push(elements[b].getAttribute('value'));
            }
        }
        /*while(++i <= count){
            doc=document.getElementById("check"+i)
            if(doc.checked)
            {checked.push(i);
            id.push(doc.getAttribute('value'));
            }

        }*/
        ch=id;
        for(var k=1;k<id.length;k++)
        {
        obj_id=" "+or+" id="+id[k];
        fin_obj=fin_obj+obj_id;
        }
        filter="id="+id[0]+fin_obj;

        layer.mergeNewParams({CQL_FILTER:filter});

        wms = new OpenLayers.Format.WMSCapabilities();
        OpenLayers.Request.GET({
            //url:"wmsURL&service=WMS&request=GetCapabilities",
            url:"http://localhost:8080/geoserver/wms/filedata?request=GetCapabilities",
            success: function(e){
                console.log(e);
                var response = wms.read(e.responseText);
                var capability = response.capability;
                for (var i=0, len=capability.layers.length; i<len; i+=1) { 
                    var layerObj = capability.layers[i];
                    if (layerObj.name === 'cite:filedata') {
                        extend=OpenLayers.Bounds.fromArray(layerObj.llbbox);
                        map.zoomToExtent(extend.transform(fromProjection,toProjection));
                        break; 
                    } 
                }
            }
        });
        position = new OpenLayers.Bounds(60.67,56.84,60.68,56.87).transform(fromProjection,toProjection);       
        }

    }
//принятие участков
    function accepting()
    {
        for(var k=0;k<ch.length;k++)
        {
              document.getElementById("check"+ch[k]).nextSibling.style.color='black';
        }
         $.post(
            "setStatus.jsp",
            {ids:ch.toString()}
         );
    }
    //удаление участков
    function deleting()
    {
         $.post(
            "deletePoly.jsp",
            {ids:ch.toString()},
           function(per){
          $("#WRAPlist").load("listing.jsp");
            }
          );

    }
    if(document.getElementsByClassName) {
        getElementsByClass = function(classList, node) {    
        return (node || document).getElementsByClassName(classList)
    }
    } else {
        getElementsByClass = function(classList, node) {            
        var node = node || document,
        list = node.getElementsByTagName('*'), 
        length = list.length,  
        classArray = classList.split(/\s+/), 
        classes = classArray.length, 
        result = [], i,j
        for(i = 0; i < length; i++) {
            for(j = 0; j < classes; j++) {
                if(list[i].className.search('\\b' + classArray[j] + '\\b') != -1) {
                    result.push(list[i])
                    break
                }
            }
        }
        return result
    }   
}

var er='${error}';
    if (er!="")
{
        alert("${error}");
    }
window.onload = createUploader;
function createUploader(){            
    var uploader = new qq.FileUploader({
        element: document.getElementById('file-uploader-demo1'),
        action: 'Upload_Servlet',
        debug: true,
        allowedExtensions:['jpg', 'jpeg', 'png', 'gif'],
        sizeLimit: 6000000, // max size   
        minSizeLimit: 11024, // min size
        onComplete: function(){
          populate();
        }
    });           
} 
</script>

</head>
<body onload="init()">
<div class="container">
<div class="content">
    <div class="ol"> <div id="map"></div> </div>
    </div>
</div>
<div class="info">
    <div class="list">
    <div class="listtitle">
    <div>
        <h2>Список участков</h2>
    </div>
    <div class="check">
        <input type="button" id="check" value="Отобразить">
    </div>
    <div class="acc">
        <input type="button" id="accept" onclick="accepting()" value="Принять">
    </div>
</div>
<div class="filelist" id="WRAPlist">
<%
Class.forName("org.postgresql.Driver");
Connection conn= null;
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgis","postgres","123456");
Statement sta = null;
sta = conn.createStatement();
String fileName= "";
Integer fileId=null;
String fileStatus ="";

ResultSet r=sta.executeQuery("SELECT id, name, status FROM filestatus");
String acc="Принят                   ";
while(r.next())
{
    fileId=r.getInt("id");
    fileName=r.getString("name");
    fileStatus=r.getString("status");   
    if(fileStatus.equalsIgnoreCase(acc))
    {
        out.write("<input type='checkbox' class='myclass' id='check"+fileId+"' name='"+fileName+"' value='"+fileId+"'/><label for=check"+fileId+">"+fileName+"</label><br>");   
  }
    else
    {
        out.write("<input type='checkbox' class='myclass' id='check"+fileId+"' name='"+fileName+"' value='"+fileId+"'/><label for=check"+fileId+" style='color:blue'>"+fileName+"</label><br>");

    }
}
r.close();
sta.close();
conn.close();

%>
</div>
 </div>
 <div class="upload">
    <div class="upload_int">
    <h2>Загрузка файлов</h2>
  <form action="" method="post" enctype="multipart/form-data">
   <div id="up">
    <input id="fileUpload1" type="file" name="fileUpload1"value="Browse..."/>
   </div>
   <div>
    <button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Загрузить</button>
    <input type="button" id="del" onclick="deleting()" value="Удалить">
   </div>
   </form>
   </div>
 <div id="file-uploader-demo1">     
    <noscript>          
        <p>Please enable JavaScript to use file uploader.</p>
        <!-- or put a simple form for upload here -->
    </noscript>

</div>
 </div>
 </div>
 <div class="clearing">&nbsp;</div>
 </body>
 </html>

I mistake here or just gonna use another method to solve this?

1 Answer 1

1

Use this jquery plugin for upload ajax upload

<script>        
        window.onload = createUploader;
        function createUploader(){            
            var uploader = new qq.FileUploader({
                element: document.getElementById('file-uploader'),
                action: 'Upload_Servlet',
                debug: true,
                allowedExtensions:['jpg', 'jpeg', 'png', 'gif'],
                sizeLimit: 6000000, // max size   
                minSizeLimit: 11024, // min size
                onComplete: function(){
                }
            });           
        }


    </script>

It May not work on IE6 but its a great plugin.

Sign up to request clarification or add additional context in comments.

17 Comments

var uploader = new qq.FileUploader this is default syntax? I dont gonna change some thing? element: document.getElementById('file-uploader') This is id of file input?
yes thats id of file input tag.and you can customize the things- like you can set the allowedExtensions that you want to allow,you can set minSizeLimit of file etc. You better follow the link in answer to make it more clear.
And another thing i cant understand in demo valums.com/files/2010/file-uploader/demo.htm dont using any uplod servlet and file upload anyway. If i write action: 'Upload_Servlet' file will be upload second time?
You can write anything in action: a servlet url ,php,even html path is allowed. the thing is you just need to return success message from whatever is called.As far as demo is concerned they may be calling a php that simply returns a success message.You need to do the same thing in your servlet.
i try do your code but, i dont see upload button. What i do wrong?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.