Use Dropzone to upload images and display back examples, and dropzone to upload images

Source: Internet
Author: User
Tags passthrough

Use Dropzone to upload images and display back examples, and dropzone to upload images

I. Problems Related to image uploading
1. introduce such code into the HTML page

    <div class="row">        <div class="col-md-12">            <form dropzone2  class="dropzone" enctype="multipart/form-data" method="post"></form>        </div>    </div>

2. Send a POST request in the command
The key code is as follows:

 var manage = angular.module('hubBrowseManageDirectives', []);    manage.directive('dropzone2', function () {        return {            restrict: 'EA',            controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {                $element.dropzone({                    url : "rest/components/"+$scope.component.name+"/"+$scope.component.version+"/images",                    autoDiscover : false,                    autoProcessQueue: true,                    addRemoveLinks: true,                    addViewLinks: true,                    acceptedFiles: ".jpg,.png",                    dictDefaultMessage: "upload head picture",                    maxFiles : "1",                    dictMaxFilesExceeded: "Only can upload one picture, repeat upload will be deleted!",                    init: function () {                     var mockFile = { name: "Filename",                                       size: 10000                                     };                     this.emit("addedfile", mockFile);                     mockFile._viewLink.href = "rest/components/"+$scope.component.name+"/"+$scope.component.version +"/"+$scope.component.image;                     mockFile._viewLink.name = $scope.component.image;                     this.emit("thumbnail", mockFile, "rest/components/"+$scope.component.name+"/"+$scope.component.version +"/"+$scope.component.image);                     this.emit("complete", mockFile);                        $(".dz-view").colorbox({                               rel:'dz-view',                                width:"70%",                               height:"80%"                        });                        this.on("error", function (file, message) {                            alert(message);                            this.removeFile(file);                        });                        this.on("success", function(file,imageInfo) {                          file._viewLink.href = imageInfo.newfile;                          file._viewLink.name = imageInfo.newfile;                           $scope.$apply(function() {                                $scope.component.image="rest/components/"+$scope.component.name+"/"+$scope.component.version+"/"+imageInfo.newfile;                           });                        });                        this.on("removedfile", function(file) {                           var removeFileUrl = file._viewLink.name;                                if($scope.component.image == removeFileUrl){                                    this.removeFile(file);                                }                          });                    }                });            }]        };    });

Note that the request method of the preceding URL must be allowed in the Angular simulation request. The format is as follows:

var hubMock = angular.module('hubMock', ['ngMockE2E']);    hubMock.run(['$httpBackend', '$http', function ($httpBackend, $http) {        $httpBackend.whenGET(/\.html/).passThrough();        $httpBackend.whenGET(/\.json/).passThrough();        $httpBackend.whenPOST(/rest\/components\/.+\/.+\/images/).passThrough();    }]);

$ HttpBackend. whenPOST (/rest \/components \/. + \/. + \/images/). passThrough (); Allow Image Upload and sending as a POST request.

3. Store the uploaded image locally.

 @POST    @Path("/{componentName: \\w+}/{version: \\d\\.\\d\\.\\d}/images")    @Produces(MediaType.APPLICATION_JSON)    public Response uploadMyComponentImage(@Context HttpServletRequest request, @PathParam("componentName") String componentName,            @PathParam("version") String version) {        Map<String, String> infoMap = componentService.uploadMyComponentImage(request, componentName, version);        return Response.ok(infoMap).build();    }

4. process the Image Upload location through the interface and its implementation class

  @Override    public Map<String, String> uploadMyComponentImage(HttpServletRequest request, String componentName, String version) {        Map<String, String> infoMap = new HashMap<String, String>();        String url = null;        try {            url = application.getStorageLocation(File.separator + componentName + File.separator + version).getAbsolutePath();        } catch (IOException e1) {            e1.printStackTrace();        }        DiskFileItemFactory factory = new DiskFileItemFactory();        ServletFileUpload upload = new ServletFileUpload(factory);        try {            Map<String, List<FileItem>> items = upload.parseParameterMap(request);            for (Entry<String, List<FileItem>> entry : items.entrySet()) {                String key = entry.getKey();                Iterator<FileItem> itr = items.get(key).iterator();                while (itr.hasNext()) {                    FileItem item = itr.next();                    String newfileName = UUID.randomUUID().toString() + "-" + item.getName();                    infoMap.put("newfile", "" + newfileName);                    File file = new File(url);                    if (!file.exists()) {                        file.mkdirs();                    }                    file = new File(url + File.separator + "img" + File.separator + newfileName);                    item.write(file);                }            }        } catch (FileUploadException e) {            e.printStackTrace();        } catch (Exception e) {            e.printStackTrace();        }        return infoMap;    }

Here, a map is returned, the key is newfile, and the value is "+ newfileName. Therefore, the image information can be obtained after the upload is successful, as shown in the following example imageInfo. newfile ;:

 this.on("success", function(file,imageInfo) {                          file._viewLink.href = imageInfo.newfile;                          file._viewLink.name = imageInfo.newfile;                           $scope.$apply(function() {                                $scope.component.image="rest/components/"+$scope.component.name+"/"+$scope.component.version+"/"+imageInfo.newfile;                           });                        });

2. How do I display images on the page?

1. Currently, the method of obtaining images on a website is mainly to send a Get request to the browser. Here, the method of actively requesting images is also used.

When the page is displayed, a request is sent:

"Rest/components/" + Scope. component. name + "/" + Scope. component. version + "/" + $ scope. component. image

The actual Request Path is as follows:

Localhost: 8080/xxxxxx/rest/components/2_component1/1.0.0/0c6684ad-84df-4e0e-8163-9e2d179814e6-Penguins.jpg

2. How does the backend accept and process requests?
See the following code to return to the browser is actually an output stream.

Key code example

/*** Get pictures OutputStream ** @ param componentName * @ param version * @ return */@ GET @ Path ("/{componentName: \ w +}/{version: \ d \\. \ d \\. \ d}/{imagePath :. +} ") @ Produces (MediaType. APPLICATION_OCTET_STREAM) public Response findImages (@ PathParam ("componentName") final String componentName, @ PathParam ("version") final String version, @ PathParam ("imagePath") final String imagePath) {StreamingOu Tput output = new StreamingOutput () {private BufferedInputStream bfis = null; public void write (OutputStream output) throws IOException, WebApplicationException {try {String filePath = ""; // determine whether the request path of the image is a long path. The if (imagePath. contains ("/") {// retrieve the image filePath = application. getStorageLocation (File. separator + componentName + File. separator + version) + File. separator + "img" + File. separator + ImagePath. split ("/") [imagePath. split ("/"). length-1];} else {// retrieve the image filePath = application. getStorageLocation (File. separator + componentName + File. separator + version) + File. separator + "img" + File. separator + imagePath;} bfis = new BufferedInputStream (new FileInputStream (filePath); int read = 0; byte [] bytes = new byte [1024]; while (read = bfis. read (bytes ))! =-1) {output. write (bytes, 0, read) ;}} catch (Exception e) {e. printStackTrace () ;}finally {try {if (bfis! = Null) {bfis. close ();} output. flush (); output. close () ;}catch (Exception e2) {e2.printStackTrace () ;}}}; // return Response to the browser. OK (output, MediaType. APPLICATION_OCTET_STREAM ). build ();}

3. When you click view, the system will request the background to return a preview of the large image. Here, the colorbox plug-in is used to preview and rotate the large image. It feels cool.

The effect is as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.