写在最前面:这篇文章年代比较久远,部分代码没有贴全,看到好多网友需要,于是找了一下,贴在文章的最后。 ——2018.07.20
网上翻阅了很多教程,但是都不全面,经过一番研究之后终于成功上传了文件
一、需要引用的资源
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/bootstrap-table/src/bootstrap-table.css">
<link rel="stylesheet" href="assets/examples.css">
<script src="assets/jquery.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/bootstrap-table/src/bootstrap-table.js"></script>
<script src="assets/ga.js"></script>
<link type="text/css" rel="stylesheet" href="bootstrap-fileinput-master/css/fileinput.css" />
<script type="text/javascript" src="bootstrap-fileinput-master/js/fileinput.js"></script>
<script type="text/javascript" src="bootstrap-fileinput-master/js/locales/zh.js"></script>
因为该插件基于Bootstrap和jQuery,所以需要引入js和css文件,同时如果想要使插件语言变成中文,也要引入对应的语言文件,中文为zh.js
二、html代码部分
<
div class=
"container-fluid">
<form
id=
"form" action=
"upload/insert" method=
"post" enctype=
"multipart/form-data">
<
div class=
"row form-group">
<label
class=
"col-md-4">图片上传:</label>
<
div class=
"col-sm-12">
<input
id=
"input-id" name=
"file" multiple type=
"file" data-show-caption=
"true">
</
div>
</
div>
</form>
</
div>
注意:有的教程在input标签上加了class=”file”,这个class会导致插件一直是英文,即语言切换失效,解决方式很简单,把class=”file”去掉即可。
三、JS代码部分
$(
function () {
initFileInput(
"input-id");
})
function initFileInput(ctrlName) {
var control = $(
'#' + ctrlName);
control.fileinput({
language:
'zh',
uploadUrl:
"upload/insert",
allowedFileExtensions: [
'jpg',
'gif',
'png'],
uploadAsync:
true,
showUpload:
true,
showRemove :
true,
showPreview :
true,
showCaption:
false,
browseClass:
"btn btn-primary",
enctype:
'multipart/form-data',
validateInitialCount:
true,
previewFileIcon:
"<i class='glyphicon glyphicon-king'></i>",
msgFilesTooMany:
"选择上传的文件数量({n}) 超过允许的最大数值{m}!",
}).on(
'filepreupload',
function(event, data, previewId, index) {
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
console.log(
'文件正在上传');
}).on(
"fileuploaded",
function (event, data, previewId, index) {
console.log(
'文件上传成功!'+data.id);
}).on(
'fileerror',
function(event, data, msg) {
console.log(
'文件上传失败!'+data.id);
})
}
其中常用的基础参数、回调函数都有注释。
四、Java代码部分
package
com.ssm.controller
import java
.io.File
import java
.util.ArrayList
import java
.util.Date
import java
.util.List
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.bind.annotation.RequestParam
import org
.springframework.web.multipart.MultipartFile
import org
.springframework.web.multipart.MultipartHttpServletRequest
import
com.diecolor.utils.Constants
import
com.diecolor.utils.FileUtil
import
com.diecolor.utils.TimeUtils
@Controller
@RequestMapping(
"/upload")
public class UploadController {
@RequestMapping(
"/insert")
public void insert(HttpServletRequest request,HttpServletResponse response
,@RequestParam(
"file") MultipartFile[] file) throws Exception{
if(file!=null&&file
.length>
0){
//组合image名称,“
List<String> fileName =new ArrayList<String>()
try {
for (int i =
0
if (!file[i]
.isEmpty()) {
//上传文件,随机名称,
";"分号隔开
fileName
.add(FileUtil
.uploadImage(request,
"/upload/"+TimeUtils
.formateString(new Date(),
"yyyy-MM-dd")+
"/", file[i], true))
}
}
//上传成功
if(fileName!=null&&fileName
.size()>
0){
System
.out.println(
"上传成功!")
Constants
.printJson(response, fileName)
}else {
Constants
.printJson(response,
"上传失败!文件格式错误!")
}
} catch (Exception e) {
e
.printStackTrace()
Constants
.printJson(response,
"上传出现异常!异常出现在:class.UploadController.insert()")
}
}else {
Constants
.printJson(response,
"没有检测到文件!")
}
}
}
uploadImage()方法:(支持随机名称)
/**
* 上传图片
* 原名称
* @param request 请求
* @param path_deposit 存放位置(路径)
* @param file 文件
* @param isRandomName 是否随机名称
* @return 完整文件路径
*/
public static String
uploadImage(HttpServletRequest request,String path_deposit,MultipartFile file,
boolean isRandomName) {
try {
String[] typeImg={
"gif",
"png",
"jpg"};
if(file!=
null){
String origName=file.getOriginalFilename();
System.out.println(
"上传的文件原名称:"+origName);
String type=origName.indexOf(
".")!=-
1?origName.substring(origName.lastIndexOf(
".")+
1, origName.length()):
null;
if (type!=
null) {
boolean booIsType=
false;
for (
int i =
0; i < typeImg.length; i++) {
if (typeImg[i].equals(type.toLowerCase())) {
booIsType=
true;
}
}
if (booIsType) {
String path=request.getSession().getServletContext().getRealPath(path_deposit);
String fileSrc=
"";
if(isRandomName){
origName=TimeUtils.formateString(
new Date(),
"yyyy-MM-dd-")+UUID.randomUUID().toString()+origName.substring(origName.lastIndexOf(
"."));
}
File targetFile=
new File(path,origName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
file.transferTo(targetFile);
fileSrc=request.getScheme()+
"://"+request.getServerName()+
":"+request.getServerPort()+request.getContextPath()+path_deposit+origName;
System.out.println(
"图片上传成功:"+fileSrc);
return fileSrc;
}
}
}
return null;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
当前使用的是SpringMVC框架,该插件上传文件的后台代码与普通文件上传的代码相同。
五、一些参数配置
showCaption:是否显示文件的标题。默认值true。 showPreview:是否显示文件的预览图。默认值true。showRemove:是否显示删除/清空按钮。默认值true。showUpload:是否显示文件上传按钮。默认是submit按钮,除非指定了uploadUrl属性。默认值true。showCancel:是否显示取消文件上传按钮。只有在AJAX上传线程中该属性才可见可用。默认值true。captionClass:在标题容器上额外的class。类型string。previewClass:在预览区域容器上的额外的class。类型string。mainClass:添加在文件上传主容器。类型string。initialDelimiter:在initialPreview属性中用于上传多个文件时的分隔符。默认值:’$$‘。initialPreview:类型string或array。显示的初始化预览内容。你可以传入一个简单的HTML标签用于显示图片、文本或文件。如果设置一个字符串,会在初始化预览图中显示一个文件。你可以在initialDelimiter属性中设置分隔符用于显示多个预览图。如果设置为数组,初始化预览图中会显示数组中所有的文件。
六、官网
http://plugins.krajee.com/file-input
七、 对网友问题的解答
1.Constants.printJson()的具体代码是什么? 答:
import
com.google.gson.Gson
import
com.google.gson.GsonBuilder
public static void printJson(HttpServletResponse response,Object obj) {
response
.setHeader(
"Access-Control-Allow-Origin",
"*")
response
.setContentType(
"text/json;charset=UTF-8")
String temp=
""
Gson gson=new GsonBuilder()
.setDateFormat(
"yyyy-MM-dd HH:mm:ss")
.create()
if (obj!=null) {
temp=gson
.toJson(obj)
}
try {
response
.getWriter()
.print(temp)
response
.getWriter()
.flush()
response
.getWriter()
.close()
} catch (IOException e) {
e
.printStackTrace()
}
}
注:该方法可以使用@ResponseBody代替
2.TimeUtils.formateString()具体实现 答:这个方法用于将Date转换为String,尴尬的是转换应是format而非formate
public static
String formateString(
Date date,
String pattern) {
SimpleDateFormat sdf
= new SimpleDateFormat(pattern);
String str
= sdf
.format(
date);
return str;
}
转载请注明原文地址: https://ju.6miu.com/read-965189.html