webuploader+springmvc實(shí)現(xiàn)圖片上傳功能
本文為大家分享了webuploader springmvc實(shí)現(xiàn)圖片上傳的具體代碼,供大家參考,具體內(nèi)容如下
jsp文件
<%@ 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>Insert title here</title> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/manage/Widget/webuploader/0.1.5/webuploader.css" rel="external nofollow" > <script src="${pageContext.request.contextPath}/manage/assets/js/jquery.min.js"></script> <script src="${pageContext.request.contextPath}/manage/Widget/webuploader/0.1.5/webuploader.js"></script> </head> <body> <h3>圖片上傳</h3> <!--dom結(jié)構(gòu)部分--> <div id="uploader-demo"> <!-- 用來存放item --> <div id="fileList" class="uploader-list"></div> <div id="upInfo" ></div> <div id="filePicker">選擇文件</div> </div> <input type="button" id="btn" value="開始上傳"> <script> //圖片上傳demo jQuery(function() { var $ = jQuery, $list = $('#fileList'), // 優(yōu)化retina, 在retina下這個(gè)值是2 ratio = window.devicePixelRatio || 1, // 縮略圖大小 thumbnailWidth = 100 * ratio, thumbnailHeight = 100 * ratio, // Web Uploader實(shí)例 uploader; // 初始化Web Uploader uploader = WebUploader.create({ // 自動(dòng)上傳。 auto: false, // swf文件路徑 swf:'${pageContext.request.contextPath }/manage/Widget/webuploader/0.1.5/Uploader.swf', // 文件接收服務(wù)端。 server: '${pageContext.request.contextPath }/uploader.action', threads:'5', //同時(shí)運(yùn)行5個(gè)線程傳輸 fileNumLimit:'10', //文件總數(shù)量只能選擇10個(gè) // 選擇文件的按鈕??蛇x。 pick: {id:'#filePicker', //選擇文件的按鈕 multiple:true}, //允許可以同時(shí)選擇多個(gè)圖片 // 圖片質(zhì)量,只有type為`image/jpeg`的時(shí)候才有效。 quality: 90, //限制傳輸文件類型,accept可以不寫 accept: { title: 'Images',//描述 extensions: 'gif,jpg,jpeg,bmp,png,zip',//類型 mimeTypes: 'image/*'//mime類型 } }); // 當(dāng)有文件添加進(jìn)來的時(shí)候,創(chuàng)建img顯示縮略圖使用 uploader.on( 'fileQueued', function( file ) { var $li = $( '<div id="' + file.id + '" class="file-item thumbnail">' + '<img>' + '<div class="info">' + file.name + '</div>' + '</div>' ), $img = $li.find('img'); // $list為容器jQuery實(shí)例 $list.append( $li ); // 創(chuàng)建縮略圖 // 如果為非圖片文件,可以不用調(diào)用此方法。 // thumbnailWidth x thumbnailHeight 為 100 x 100 uploader.makeThumb( file, function( error, src ) { if ( error ) { $img.replaceWith('<span>不能預(yù)覽</span>'); return; } $img.attr( 'src', src ); }, thumbnailWidth, thumbnailHeight ); }); // 文件上傳過程中創(chuàng)建進(jìn)度條實(shí)時(shí)顯示。 uploadProgress事件:上傳過程中觸發(fā),攜帶上傳進(jìn)度。 file文件對(duì)象 percentage傳輸進(jìn)度 Nuber類型 uploader.on( 'uploadProgress', function( file, percentage ) { var $li = $( '#'+file.id ), $percent = $li.find('.progress span'); // 避免重復(fù)創(chuàng)建 if ( !$percent.length ) { $percent = $('<p class="progress"><span></span></p>') .appendTo( $li ) .find('span'); } $percent.css( 'width', percentage * 100 + '%' ); }); // 文件上傳成功時(shí)候觸發(fā),給item添加成功class, 用樣式標(biāo)記上傳成功。 file:文件對(duì)象, response:服務(wù)器返回?cái)?shù)據(jù) uploader.on( 'uploadSuccess', function( file,response) { $( '#'+file.id ).addClass('upload-state-done'); //console.info(response); $("#upInfo").html("<font color='red'>"+response._raw+"</font>"); }); // 文件上傳失敗 file:文件對(duì)象 , code:出錯(cuò)代碼 uploader.on( 'uploadError', function(file,code) { var $li = $( '#'+file.id ), $error = $li.find('div.error'); // 避免重復(fù)創(chuàng)建 if ( !$error.length ) { $error = $('<div class="error"></div>').appendTo( $li ); } $error.text('上傳失敗!'); }); // 不管成功或者失敗,文件上傳完成時(shí)觸發(fā)。 file: 文件對(duì)象 uploader.on( 'uploadComplete', function( file ) { $( '#'+file.id ).find('.progress').remove(); }); //綁定提交事件 $("#btn").click(function() { console.log("上傳..."); uploader.upload(); //執(zhí)行手動(dòng)提交 console.log("上傳成功"); alert("上傳成功!"); }); }); </script> </body> </html>
springMvc 的 servlet加入以下代碼(允許上傳):
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
引入的包
commons-io-1.3.2.jar
commons-fileupload-1.2.1.jar
java代碼
package com.shopping.controller; import java.io.File; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; /** * @author MAZN * @date 創(chuàng)建時(shí)間:2017年5月2日 下午10:02:36 * @parameter * @return */ @Controller public class UploadImgController { int counter = 0; @RequestMapping("/uploader") public void upload(HttpServletRequest request,HttpServletResponse response){ //String fileName; // File tagetFile; System.out.println("收到圖片!"); MultipartHttpServletRequest Murequest = (MultipartHttpServletRequest)request; Map<String, MultipartFile> files = Murequest.getFileMap();//得到文件map對(duì)象 //String upaloadUrl = request.getSession().getServletContext().getRealPath("/")+"upload/";//得到當(dāng)前工程路徑拼接上文件名 String t=Thread.currentThread().getContextClassLoader().getResource("").getPath(); int num=t.indexOf(".metadata"); String small = "small"; String upaloadUrl=t.substring(1,num).replace('/', '\\')+"image\\"+small+"\\"; //+"項(xiàng)目名\\WebContent\\文件"; File dir = new File(upaloadUrl); System.out.println(upaloadUrl); String img_url = upaloadUrl;//圖片路徑 if(!dir.exists())//目錄不存在則創(chuàng)建 dir.mkdirs(); for(MultipartFile file :files.values()){ counter++; String fileName=file.getOriginalFilename(); File tagetFile = new File(upaloadUrl+fileName);//創(chuàng)建文件對(duì)象 img_url += fileName; if(!tagetFile.exists()){//文件名不存在 則新建文件,并將文件復(fù)制到新建文件中 try { tagetFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } try { file.transferTo(tagetFile); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println(img_url); System.out.println("接收完畢"+counter); } }
參考:WebUploader客戶端批量上傳圖片 后臺(tái)使用springMVC
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Java中的迭代迭代器Iterator與枚舉器Enumeration
Iterator與Enumeration分別是實(shí)現(xiàn)迭代器和枚舉器類的接口,下面就帶大家來詳解Java中的迭代迭代器Iterator與枚舉器Enumeration,以及它們之間的區(qū)別.2016-05-05rabbitmq五種模式詳解(含實(shí)現(xiàn)代碼)
這篇文章主要介紹了rabbitmq五種模式詳解(含實(shí)現(xiàn)代碼),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04Java中使用BigDecimal進(jìn)行精確運(yùn)算
這篇文章主要介紹了Java中使用BigDecimal進(jìn)行精確運(yùn)算的方法,非常不錯(cuò),需要的朋友參考下2017-02-02被遺忘的Java關(guān)鍵字transient的使用詳解
在 Java 中,transient 是一個(gè)關(guān)鍵字,用于指定一個(gè)類的字段(成員變量)在序列化時(shí)應(yīng)該被忽略。本文將通過示例為大家簡(jiǎn)單講講transient的使用,需要的可以參考一下2023-04-04java poi導(dǎo)出excel時(shí)如何設(shè)置手動(dòng)換行
這篇文章主要介紹了java poi導(dǎo)出excel時(shí)如何設(shè)置手動(dòng)換行,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06