Search code examples
web-servicesservletsmultipart

How to pass multipart file data to a web service


I wanna do something like this.

1.Uploading a file from a jsp in multipart

2.Calling a servlet

3.In dopost of that servlet i wanna call a webservice which takes all the params passed by jsp to servlet along with the multipart data.

dopost(javax.servlet.http.HttpServletRequest request,
            javax.servlet.http.HttpServletResponse response){

    webserviceMethod(request,response);

}

I'm stuck on third point where I can set all request params to webservice method. But I don't know how to pass multipart file data to that websevice. I failed to do so. How can i do that part??


Solution

  • Have a look at that jquery plugin:

    http://jquery.malsup.com/form/

    I'm also using this in my Application together with a java servlet:

     uploadImage: function (e) {
            var self = this;
            self.ignoreDrag(e);
            if ($('#feed_imageUploader').find('input').hasClass('error')) {
                return;
            }
            //cant put this in an model - ajaxSubmit has no done callback
            $('#img_uploaded h1').text(polyglot.t('iview.loading'));
            $('#feed_imageUploader').ajaxSubmit({
                target: '#img_uploaded',
                type: "POST",
                url: path.apiPath + 'item.uploadImg/' + self.itemId + '/' + token,
                dataType: "text",
                async: true,
                success: function () {
                    self.afterUploadImage();
                }
            });
    
        },
     afterUploadImage: function () {
            var self = this;
            self.changed = true;
            var xFactorItemImage = 0;
            var yFactorItemImage = 0;
            var randomnumber = Math.floor(Math.random() * 10100000);
            $('#img_uploaded').html("<img src=\"" + path.tempImage + userId + "_" + self.itemId + ".jpg?id=" + randomnumber + "\" style=\"display:none\" id=\"cropPhoto_uploaded\">");
            var theImage = new Image();
            var cropPhoto = $('#cropPhoto_uploaded');
            theImage.src = cropPhoto.attr("src");
            var widthPhoto = 0;
            var heightPhoto = 0;
            var NwidthPhoto = 0;
            var NheightPhoto = 0;
            $(theImage).load(function () {
                $('#img_uploaded h1').empty();
                $('#additemimage').hide();
                NwidthPhoto = theImage.width;
                NheightPhoto = theImage.height;
                cropPhoto.css({
                    maxHeight: $('#img_uploaded').height() + 'px',
                    maxWidth: $('#img_uploaded').width() + 'px'
                });
                cropPhoto.show();
                $('#addimage_upload').fadeIn(aSpeed.middle);
                widthPhoto = cropPhoto.width();
                heightPhoto = cropPhoto.height();
                xFactorItemImage = NwidthPhoto / widthPhoto;
                yFactorItemImage = NheightPhoto / heightPhoto;
                cropPhoto.Jcrop({
                    setSelect: helper.getMiddleSelectionOfImage(widthPhoto, heightPhoto, widthPhoto, heightPhoto),
                    bgOpacity: 0.3,
                    onChange: showItemImageCoords,
                    onSelect: showItemImageCoords
                });
            });
    
            function showItemImageCoords(c) {
                $('#x111').val(parseInt(xFactorItemImage * c.x));
                $('#y111').val(parseInt(yFactorItemImage * c.y));
                $('#x222').val(parseInt(xFactorItemImage * c.w));
                $('#y222').val(parseInt(yFactorItemImage * c.h));
            }
        },
    

    And the servlet part:

    public void UploadImage(HttpServletRequest request, String filename, String folder,String bucketname) {
        File file;
        PropertyReader mainconf = new PropertyReader();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items ;
        mainconf.getProb("conf/MainConfig.properties");
        s3 s3=new s3();
        try {
            items = upload.parseRequest(request);
            // Process the uploaded file items
            Iterator i = items.iterator();
    
            //Iterate through the items
            String finalPath = "";
            FileItem fi;
            while (i.hasNext()) {
                fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    // Get the uploaded file parameters               
                    String your_os = System.getProperty("os.name").toLowerCase();
                    String workingDir = "images";
                    finalPath = mainconf.read("imagePath");
                    if (your_os.indexOf("win") >= 0) {
                        finalPath = finalPath + workingDir + "\\" + folder + "\\";
                    } else if (your_os.indexOf("nix") >= 0 || your_os.indexOf("nux") >= 0) {
                        finalPath = finalPath + workingDir + "/" + folder + "/";
                    } else {
                        finalPath = finalPath + workingDir + "{others}" + folder + "{others}";
                    }
                    file = new File(finalPath + filename + ".jpg");
                    fi.write(file);
                    s3.writeFile(bucketname, file, filename+".jpg");
                    file.delete();
    
                }
                break;
            }
    
        } catch (Exception ex) {
            Logger.getLogger(UploadItemImage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }