使用Dropzone上传图片及回显示例

一、图片上传所涉及到的问题
1、HTML页面中引入这么一段代码

    <div class="row">

        <div class="col-md-12">

            <form dropzone2  class="dropzone" enctype="multipart/form-data" method="post"></form>

        </div>

    </div>

2、 在指令中发送POST请求
关键代码如下

 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);
                                }

                          });

                    }
                });

            }]
        };
    });

注意上述URL的请求方式,要在Angular模拟请求中放行。格式如下:

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(); 放行图片上传发送是POST 请求。

3、处理上传图片的请求将其存储在本地

 @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、通过接口及其实现类来处理图片上传的位置

  @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;
    }

在这里返回的是一个map, key是newfile,value是”” + newfileName,因此在上传成功后就可以取得图片的信息,如下示例 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;
                           });

                        });

二、页面中的图片如何进行回显?

1、现今的网站上图片上的获取方式主要是以Get请求的方式传回图片流到浏览器端,这里同样采用请求主动获取图片的方式。

图片回显

页面回显时会主动发送请求:

“rest/components/”+ scope.component.name+"/"+ scope.component.version +”/”+$scope.component.image

真实请求路径是这样的:

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

2、后台如何接受请求,处理请求呢?
参见以下代码,返回到浏览器的实际上就是一个输出流。

关键代码示例

 /**
     * 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) {
        StreamingOutput output = new StreamingOutput() {

            private BufferedInputStream bfis = null;

            public void write(OutputStream output) throws IOException, WebApplicationException {

                try {
                    String filePath = "";
        //判断图片的请求路径是否长路径,这个根据需求而来的
                    if (imagePath.contains("/")) {
                    //取出图片
                        filePath = application.getStorageLocation(File.separator + componentName + File.separator + version) + File.separator + "img"
                                + File.separator + imagePath.split("/")[imagePath.split("/").length - 1];

                    } else {
                      //取出图片
                        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.ok(output, MediaType.APPLICATION_OCTET_STREAM).build();

    }

3、当点击view时,又会去请求后台返回预览大图图像,这里使用了colorbox插件来进行大图像的预览和轮播显示,感觉很酷的样子。

效果如下所示:
这里写图片描述

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Dropzone 是一个基于 HTML、CSS 和 JavaScript 的开源库,用于实现拖拽上传文件的功能。Dropzone 具有强大的可扩展性和自定义性,可以很容易地集成到你的项目中。 使用 Dropzone 实现拖拽上传文件并回显的代码如下: HTML: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>使用 Dropzone 拖拽上传文件</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dropzone/dist/dropzone.css"> </head> <body> <form action="upload.php" class="dropzone" id="my-dropzone"></form> <ul id="file-list"></ul> <script src="https://cdn.jsdelivr.net/npm/dropzone"></script> <script src="upload.js"></script> </body> </html> ``` JavaScript: ```javascript Dropzone.autoDiscover = false; var myDropzone = new Dropzone("#my-dropzone", { url: "upload.php", paramName: "file", maxFilesize: 2, // 上传文件大小限制,单位为 MB maxFiles: 10, // 最多上传文件数量限制 addRemoveLinks: true, // 是否显示删除链接 dictRemoveFile: '删除文件', // 删除文件的链接文字 dictDefaultMessage: '将文件拖到此处上传', // 默认的提示消息 dictFallbackMessage: '您的浏览器不支持拖拽上传文件', // 浏览器不支持拖拽上传时的提示消息 dictFileTooBig: '文件大小超过限制', // 文件大小超过限制时的提示消息 dictInvalidFileType: '文件类型不支持', // 文件类型不支持时的提示消息 init: function() { this.on("success", function(file, response) { console.log(response); // 回显上传成功的文件信息 // 显示文件列表 var li = document.createElement('li'); li.innerHTML = file.name; document.getElementById('file-list').appendChild(li); }); } }); ``` 在上面的代码中,我们首先将 Dropzone 的样式文件和库文件引入到 HTML 中,然后在 HTML 文件中添加一个表单,表单的 class 设置为 `dropzone`,id 设置为 `my-dropzone`,这样就可以让 Dropzone 自动将表单转换为拖拽上传区域。在 JavaScript 中,我们首先设置了 `Dropzone.autoDiscover = false;`,这样就不会自动扫描 HTML 中的表单进行转换,而是通过 `new Dropzone()` 的方式来初始化 Dropzone。在初始化时,我们通过 `url` 参数指定了上传文件的处理地址,通过 `paramName` 参数指定了文件参数名,通过 `maxFilesize` 和 `maxFiles` 参数分别设置了上传文件大小和数量的限制,通过 `addRemoveLinks` 和 `dictRemoveFile` 参数控制是否显示删除链接和删除链接的文字。在 `init` 回调函数中,我们通过 `success` 事件回调函数来获取上传成功的文件信息并回显到页面上。 需要注意的是,因为上传文件使用了 `Dropzone` 对象,所以需要使用服务器端代码来进行处理,这里使用了 `upload.php` 来处理上传文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值