1.导入包引入js
导入spring包以及如下包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.spring.xml配置文件
- <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <property name="defaultEncoding" value="UTF-8"/>
- <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
- <!-- 不在这里限制了,后台各自进行限制了
- <property name="maxUploadSize" value="2000000"/>
- -->
- </bean>
- <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
- <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
- <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <property name="exceptionMappings">
- <props>
- <!-- 遇到MaxUploadSizeExceededException异常时,跳转到/page/html/errorGolbal.html页面 -->
- <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/page/html/errorGolbal.html</prop>
- </props>
- </property>
- </bean>
3.fileupload.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<!DOCTYPE html>
<html>
<head>
<title>文件上传</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<body>
<body>
<div >
<form modelAttribute="uploadInfo" id="uploadForm" name="uploadForm" action="bg/upload" method="post">
<div id="fileuploaddiv">
上传文件:<input type="file" id="apkFile" name="file"/>
<input type="button" value="上传" οnclick="ajaxFileUpload('apkFile','apkFileTip','img','filename','fileuploaddiv')"/>
<input type="text" id="filename" name="filename"/>
<span id="apkFileTip" style="width:250px"></span>
</div>
<div class="">
<button type="submit" class="btn">提交</button>
</div>
<form>
</div>
</body>
<script type="text/javascript">
/*
*fileid上传input id
*resulttip 返回结果
*type 上传类型
*returnfileurl 成功上传后的文件路径
*/
var num =1;
function ajaxFileUpload(fileid, resulttip, type, returnfileurl,fileuploaddiv)
{
var fileiddata = $('#'+fileid).val();
if(fileiddata == null || fileiddata ==''){
$('#'+resulttip).html('请选择文件');
return false;
}else if (type == 'img'){
if (!/\.(jpg|jpeg|png|JPEG|JPG|PNG)$/.test(fileiddata)){
alert("图片类型必须是.jpeg,jpg,png中的一种");
$('#'+fileid).val("");
return false;
}
}
//firefox获取的是文件名,IE获取的是全路径名,正则表达式截取文件名,判断文件名的长度
var arrdata = fileiddata.split(/\\/);
if(arrdata[arrdata.length-1].length >30){
$('#'+resulttip).html('文件名超过限定30字符的长度');
$('#'+fileid).val("");
return false;
}
$('#'+resulttip).html('文件上传中');
$.ajaxFileUpload
(
{
url:'file/fileupload',//用于文件上传的服务器端请求地址
secureuri:false,//一般设置为false
fileElementId:fileid,//文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'json',//返回值类型 一般设置为json
type : 'POST',
timeout:1200000, // 超时校验 120秒超时
success: function (data) //服务器成功响应处理函数
{
if(data.result=='suc'){
$('#'+resulttip).html('添加成功');
$('#'+fileid).val("");
if($('#'+returnfileurl).val() == null || $('#'+returnfileurl).val() ==''){
$('#'+returnfileurl).val(data.filename);
}else{
$('#'+returnfileurl).val($('#'+returnfileurl).val()+","+data.filename);
}
if(type == 'img'){
$('#'+fileuploaddiv).append("<div id='filediv"+num+"'>文件:"+fileiddata+"<a href='javascript:void(0)' οnclick='filedelete(\"filediv"+num+"\",\""+returnfileurl+"\",\""+data.filename+"\")'>删除</a><br/></div>");
num=num+1;
}
return false;
}else if(data.result=='fnull'){
$('#'+resulttip).html('上传的文件不是图片类型的文件');
$('#'+fileid).val("");
}else if(data.result=='size2big'){
$('#'+resulttip).html('文件尺寸超过限制,尺寸界定在2560*10240范围内');
$('#'+fileid).val("");
}else if(data.result=='file2big'){
$('#'+resulttip).html('文件大小超过限制,大小界定在10M范围内');
$('#'+fileid).val("");
}else if(data.result=='exe'){
$('#'+resulttip).html('文件格式不支持');
$('#'+fileid).val("");
}else{
$('#'+resulttip).html('添加失败');
$('#'+fileid).val("");
}
},
error: function (data, status, e)//服务器响应失败处理函数
{
if('SyntaxError: illegal character' == e){
$('#'+result).html('文件大小超过限制');
$('#'+item).val("");
}else if('SyntaxError: syntax error' == e){
$('#'+result).html('文件上传有误');
$('#'+item).val("");
}else if('SyntaxError: 语法错误' == e){
$('#'+result).html('文件大小超过限制');
$('#'+item).val("");
}else{
$('#'+result).html('上传超时');
$('#'+item).val("");
}
}
}
)
return false;
}
function filedelete(filedivnum,returnfileurl,fileName){
var returnfileurlvalue = $("#"+returnfileurl).val();
returnfileurlvalue = returnfileurlvalue.replace(","+fileName,"");
returnfileurlvalue = returnfileurlvalue.replace(fileName,"");
$("#"+returnfileurl).val(returnfileurlvalue);
$("#"+filedivnum).remove();
$.ajax({
url : 'file/filedelete',
type : 'POST',
dataType : 'json',
data:{fileName:fileName},
async : false,
error : function() {
alert('Operate Failed!');
},
success : function(data) {
if (data.result=='suc'){
//alert('删除成功!');
}
}
});
};
</script>
</html>4.FileController.java(此处上上传到阿里云服务器)
package com.zhkj.mgmt.user.web;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.zhkj.utils.FileOss;
import com.zhkj.utils.FileUtil;
@Controller
@RequestMapping("/file")
public class FileController {
/**
* 进入图片上传页
*/
@RequestMapping(value="/gofileupload",method= RequestMethod.GET)
public String gofileupload(){
return "fileupload";
}
/**
* ajax上传图片
*/
@RequestMapping(value = "/fileupload", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(@RequestParam(required = false) MultipartFile file, final HttpServletRequest request) {
if (file.isEmpty()){
return "{\"result\":\"fail\"}";
}
if(file.getOriginalFilename().endsWith(".exe")){
return "{\"result\":\"exe\"}";
}
//获取后缀名,转为小写存储
String suffix = (FileUtil.getExtensionName(file.getOriginalFilename())).toLowerCase();
//获取文件名
String saveName = createDateFileName(suffix);
System.out.println(saveName);
JSONObject result = new JSONObject();
try {
if(file.getContentType().startsWith("image")){
BufferedImage buff = ImageIO.read(file.getInputStream());
if(buff == null){ // 如果上传的图片损坏,或者上传的图片为改后缀得来的,在转为图片流的时候,获得的图片流为NULL,再获取尺寸报空指针
return "{\"result\":\"fnull\"}";
}
if(buff.getWidth() > 2560 || buff.getHeight() > 10240){ //图片尺寸限制在 2560*10240
return "{\"result\":\"size2big\"}";
}
}
/*if(file.getSize()>(10*1024*1024)){ //文件上传控制在10M内,图片和附件都在控制范围内: 10*1024*1024
return "{\"result\":\"file2big\"}";
}*/
FileOss.ossuploadFile(saveName, file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.put("result", "fail");
return result.toString();
}
result.put("result", "suc");
result.put("filename", saveName);
return result.toString();
}
public static String createDateFileName(String suffix) {
String returnPath = null;
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileStr = sf.format(new Date()) + new Random().nextInt(10000);
String srcFileName = fileStr + "." + suffix;
String tempPath = srcFileName.substring(0, 4)
+ srcFileName.substring(4, 6) + "/"
+ srcFileName.substring(6, 8) + "/"
+ srcFileName.substring(8, 10) + "/";
returnPath = tempPath + srcFileName;
return returnPath;
}
/**
* ajax上传图片
*/
@RequestMapping(value = "/filedelete", method = RequestMethod.POST)
@ResponseBody
public String filedelete(HttpServletResponse response,@RequestParam String fileName) {
JSONObject result = new JSONObject();
try {
FileOss.ossdeleteFile(fileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
result.put("result", "fail");
return result.toString();
}
result.put("result", "suc");
return result.toString();
}
}