webuploader+springmvc實現(xiàn)圖片上傳功能
更新時間:2018年09月08日 15:27:57 作者:MAZN36
這篇文章主要為大家詳細介紹了webuploader+springmvc實現(xiàn)圖片上傳功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文為大家分享了webuploader springmvc實現(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結構部分-->
<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下這個值是2
ratio = window.devicePixelRatio || 1,
// 縮略圖大小
thumbnailWidth = 100 * ratio,
thumbnailHeight = 100 * ratio,
// Web Uploader實例
uploader;
// 初始化Web Uploader
uploader = WebUploader.create({
// 自動上傳。
auto: false,
// swf文件路徑
swf:'${pageContext.request.contextPath }/manage/Widget/webuploader/0.1.5/Uploader.swf',
// 文件接收服務端。
server: '${pageContext.request.contextPath }/uploader.action',
threads:'5', //同時運行5個線程傳輸
fileNumLimit:'10', //文件總數(shù)量只能選擇10個
// 選擇文件的按鈕??蛇x。
pick: {id:'#filePicker', //選擇文件的按鈕
multiple:true}, //允許可以同時選擇多個圖片
// 圖片質(zhì)量,只有type為`image/jpeg`的時候才有效。
quality: 90,
//限制傳輸文件類型,accept可以不寫
accept: {
title: 'Images',//描述
extensions: 'gif,jpg,jpeg,bmp,png,zip',//類型
mimeTypes: 'image/*'//mime類型
}
});
// 當有文件添加進來的時候,創(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實例
$list.append( $li );
// 創(chuàng)建縮略圖
// 如果為非圖片文件,可以不用調(diào)用此方法。
// thumbnailWidth x thumbnailHeight 為 100 x 100
uploader.makeThumb( file, function( error, src ) {
if ( error ) {
$img.replaceWith('<span>不能預覽</span>');
return;
}
$img.attr( 'src', src );
}, thumbnailWidth, thumbnailHeight );
});
// 文件上傳過程中創(chuàng)建進度條實時顯示。 uploadProgress事件:上傳過程中觸發(fā),攜帶上傳進度。 file文件對象 percentage傳輸進度 Nuber類型
uploader.on( 'uploadProgress', function( file, percentage ) {
var $li = $( '#'+file.id ),
$percent = $li.find('.progress span');
// 避免重復創(chuàng)建
if ( !$percent.length ) {
$percent = $('<p class="progress"><span></span></p>')
.appendTo( $li )
.find('span');
}
$percent.css( 'width', percentage * 100 + '%' );
});
// 文件上傳成功時候觸發(fā),給item添加成功class, 用樣式標記上傳成功。 file:文件對象, response:服務器返回數(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:文件對象 , code:出錯代碼
uploader.on( 'uploadError', function(file,code) {
var $li = $( '#'+file.id ),
$error = $li.find('div.error');
// 避免重復創(chuàng)建
if ( !$error.length ) {
$error = $('<div class="error"></div>').appendTo( $li );
}
$error.text('上傳失敗!');
});
// 不管成功或者失敗,文件上傳完成時觸發(fā)。 file: 文件對象
uploader.on( 'uploadComplete', function( file ) {
$( '#'+file.id ).find('.progress').remove();
});
//綁定提交事件
$("#btn").click(function() {
console.log("上傳...");
uploader.upload(); //執(zhí)行手動提交
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)建時間: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對象
//String upaloadUrl = request.getSession().getServletContext().getRealPath("/")+"upload/";//得到當前工程路徑拼接上文件名
String t=Thread.currentThread().getContextClassLoader().getResource("").getPath();
int num=t.indexOf(".metadata");
String small = "small";
String upaloadUrl=t.substring(1,num).replace('/', '\\')+"image\\"+small+"\\";
//+"項目名\\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)建文件對象
img_url += fileName;
if(!tagetFile.exists()){//文件名不存在 則新建文件,并將文件復制到新建文件中
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客戶端批量上傳圖片 后臺使用springMVC
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
詳解Java中的迭代迭代器Iterator與枚舉器Enumeration
Iterator與Enumeration分別是實現(xiàn)迭代器和枚舉器類的接口,下面就帶大家來詳解Java中的迭代迭代器Iterator與枚舉器Enumeration,以及它們之間的區(qū)別.2016-05-05

