上传图片之前也没研究过,现在项目碰到了,就做一下记录
jsp:
<tr >
<td class="tableleft">头像<font color="red">*</font></td>
<td> <input type="file" name="picture" onchange="previewImage(this, 'prvid')" multiple="multiple"> </td>
</tr>
<td>
<a href="javascript:void(0);" class="btn btn-info" onclick="sub();">保存</a>
</td>
js:
function previewImage(file, prvid) {
/* file:file控件
* prvid: 图片预览容器
*/
var tip = "Expect jpg or png or gif!"; // 设定提示信息
var filters = {
"jpeg" : "/9j/4",
"gif" : "R0lGOD",
"png" : "iVBORw"
}
var prvbox = document.getElementById(prvid);
prvbox.innerHTML = "";
if (window.FileReader) { // html5方案
for (var i = 0, f; f = file.files[i]; i++) {
var fr = new FileReader();
fr.onload = function(e) {
var src = e.target.result;
if (!validateImg(src)) {
alert(tip)
} else {
showPrvImg(src);
}
}
fr.readAsDataURL(f);
}
} else { // 降级处理
if (!/\.jpg$|\.png$|\.gif$/i.test(file.value)) {
alert(tip);
} else {
showPrvImg(file.value);
}
}
function validateImg(data) {
var pos = data.indexOf(",") + 1;
for ( var e in filters) {
if (data.indexOf(filters[e]) === pos) {
return e;
}
}
return null;
}
function showPrvImg(src) {
var img = document.createElement("img");
img.src = src;
prvbox.appendChild(img);
}
}
function sub(){
var password = $("[name=password]").val();
var user_name = $("[name=user_name]").val();
var picture = $("[name=picture]").val();
var falg = 0;
if(password.length < 6){
swal("错误提示!", "密码长度不能少于6个字符!", "error");
return;
}
if(password.length > 20){
swal("错误提示!", "密码长度不能超过20个字符!", "error");
return;
}
if('' == user_name || null == user_name){
swal("错误提示!", "登录名不能为空!", "error");
return;
}
if(picture.length > 0){
picture = picture.substr(picture.lastIndexOf(".")+1);
var pics = new Array("bmp","JPG","JPEG","PNG","GIF");
for(var i=0;i<pics.length;i++){
if (pics[i].toLowerCase() == picture.toLowerCase()){
falg = 1;
}
}
}else{
falg = 1;
}
if(falg == 1){
$("#form").submit();
}else{
alert("请选择图片上传");
}
}
java:
@RequestMapping(value={"/updateSetting"}, method={RequestMethod.POST, RequestMethod.GET})
public String updateSetting(HttpServletRequest request,UserInfo UserInfo,@RequestParam("picture") MultipartFile picture){
logger.info("修改系统用户");
//图片路径
String path = request.getSession().getServletContext().getRealPath(ReadConfigUtil.getProperty("EXCEL_PIC_PATH"));
if(picture.getSize() > 0) {
String picName = picture.getOriginalFilename();
if(getPic(picName)) {
String ext = picName.substring(picName.lastIndexOf("."));
String fileName = UserInfo.getLogin_name() +ext;
List<File> fileList = getFileList(path);
for (File file : fileList) {
String name = file.getName();
name = name.substring(0, name.lastIndexOf("."));
if(name.equalsIgnoreCase(String.valueOf(UserInfo.getLogin_name()))) {
file.delete();
}
}
File dir = new File(path,fileName);
if(!dir.exists()){
dir.mkdirs();
}
try {
picture.transferTo(dir);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
UserInfo.setUpdate_date(new Date());
userInfoService.updateUser(UserInfo);
return "redirect:/user/toSetting";
}
private static boolean getPic(String fileName) {
String pic = ReadConfigUtil.getProperty("PICS");
String[] pics = pic.split(",");
for (int i = 0; i < pics.length; i++) {
if(fileName.substring(fileName.lastIndexOf(".")+1).equalsIgnoreCase(pics[i])) {
return true;
}
}
return false;
}
/**
* 获取文件夹下的所有文件
* @param strPath
* @return
*/
private static List<File> getFileList(String strPath) {
List<File> filelist = new ArrayList<File>();
File dir = new File(strPath);
File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
if (files != null) {
for (int i = 0; i < files.length; i++) {
filelist.add(files[i]);
}
}
return filelist;
}
配置文件:
EXCEL_PIC_PATH=WEB-INF/classes/picture/
NOPIC_NAME=NOPIC.png
#上传图片类型(不区分大小写)
PICS=bmp,JPG,JPEG,PNG,GIF