使用Dropzone上傳圖片及回顯樣本,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外掛程式來進行大映像的預覽和輪播顯示,感覺很酷的樣子。
效果如下所示: