1、首先导入包
<script src="assets/scripts/back/uploadfile.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-fileinput/4.4.7/js/fileinput.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-fileinput/4.4.7/js/locales/zh.min.js"></script> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap-fileinput/4.4.7/css/fileinput.css"> /* css样式 */
注:实现还要导入bootstrap和jquery的包。
2、JSP页面
<div class="file-loading" > /* 插件自带导入的css格式 */
<input id="modifyfile" name="file" type="file"> /* name一定要有,方便action里面取值 */
</div>
<div id="modifyfile_error"></div>
3、js代码
$("#scene").fileinput({
language : 'zh',
showCaption : true,
showUpload : true,
showCancel : false,
showRemove : false,
maxFileSize : 2048,
autoReplace: true,
uploadUrl:"scene_addFile", //上传文件路径 strutsaction名_方法名
//uploadExtraData //上传文件时额外传递的参数设置
elErrorContainer : '#scene-file',
allowedFileExtensions : [ "txt"],
showPreview :false,
slugCallback : function(filename) { /* 文件被选择后会调用到这个方法,可以在action里边定义一个String fileFileName接受值,自己试过,删掉这方法后好像会收不到值 */
return filename.replace('(', '_').replace(']', '_');
}
});
$('#scene').on("fileuploaded", function(event, data, previewId, index) { /* 上传成功后调用的回调函数 */
var result = data.response; //后台返回的json
console.log('文件上传成功!'+result.fileAdress);
$("#scenefile").val(result.fileAdress);
});
4、acntion里面
public void addFile() throws Exception{
String path = ServletActionContext.getServletContext().getRealPath("/");
File tempfile = new File(path); // 如果文件夹不存在创建
if (!tempfile.exists()) {
tempfile.mkdir();
}
final Map<String, Object> result = new HashMap<String, Object>();
result.put("status", "success");
try{
if(file != null && fileFileName != null){ //判断是否有文件
UploadUtil.upload(file ,fileFileName, path); //自定义的类,方法在下面
}
result.put("fileAdress",fileFileName);
}catch(Exception e){
e.printStackTrace();
result.put("status", "error");
response.getWriter().print(new GsonBuilder().create().toJson(result));
}finally{
response.setCharacterEncoding("UTF-8");
response.getWriter().print(new GsonBuilder().create().toJson(result)); //封装为json对象后传出
}
}
public static String upload(File file , String fileName ,String savaPath ) throws IOException{
//文件上传路径
String uploadfilePath = savaPath+"assets\\file\\"; //自己定
System.out.println(uploadfilePath);
File uploadfile = new File(uploadfilePath);
//判断文件夹是否存在,如果不存在则创建文件夹
if (!uploadfile.exists()) {//先创建uploadfile文件夹
uploadfile.mkdir();
}
File tempFile=new File(uploadfilePath, fileName);
FileOutputStream fos = new FileOutputStream(tempFile);
InputStream input = new FileInputStream(file);
// 一次30kb
byte[] readBuff = new byte[1024 * 30];
int count = -1;
while ((count = input.read(readBuff, 0, readBuff.length)) != -1) {
fos.write(readBuff, 0, count);
}
fos.flush();
fos.close();
input.close();
return null;
}
以上则为bootstrap的传文件流程,此流程只会将文件放到文件夹里,若要数据库记录,则可以通过回调函数,将文件名赋给jsp页面一隐藏文本框,然后跟随其他信息通过表单被提交。