文件上传

项目开发中遇到了文件上传的需求,之前没有开发过,琢磨了很长时间,也踩了很多坑,特此记录一下;(前后端不分离的)。

具体的场景及逻辑:

页面点击上传按钮,跳转到上传页面,在上传页面,点击对应信息的上传按钮,实现文件的上传,并将上传后的地址返回到前端页面展示;

前端用到的主要技术: bootstrap-fileinput;

具体实现:

前端页面:

1、引入bootstrap-fileinput插件:路径需要注意;

<script src="../bootstrap-fileinput/js/fileinput.min.js"></script>
<script src="../bootstrap-fileinput/js/locales/zh.js"></script>
<link rel="stylesheet"  href="../bootstrap-fileinput/css/fileinput.min.css">

2、点击上传按钮,打开上传文件的模态框;

// 按钮代码 
<div class="col-sm-6">
  <label class="col-sm-4 control-label">图片1:</label>
  <div class="col-sm-2">
  <input type="button" class="btn btn-primary" value="上传" onclick="selectFile('p1','file','这是p1')"/>
  <p class="ncUpload"></p>   // 用来显示上传后的路径
  </div>
</div>
// 按钮对应的点击事件js function selectFile(id,name,title){ $("#uploadBody").text("");  // 将模态框的初始body体置空; var html = "<input id='"+id+"' name='"+name+"' type='file' class='file-loading'>"; $("#uploadBody").append(html);  // 将模态框赋予上传文件的input $("#myUploadTitle").html(title);  // 动态显示模态框的hearer的title值; $("#"+id).fileinput({  // 这个是重点,实现文件的上传; language: 'zh',   //设置语言 uploadUrl: BASE_CONST.CONTEXT_PATH + "/vldr/file/fileUpload", // 上传的地址,即调用的后端接口; allowedFileExtensions: ['jpg', 'gif', 'png', 'jpeg','pdf'],  // 接收的文件后缀,即允许上传的文件类型; // uploadExtraData:{"id": $("#id").val(),"name": $("#name").val(),"age": $("#age").val()}, // 调用接口时,附带的其他参数,如果有的话; uploadAsync: false,   //默认异步上传 showUpload: true,   //是否显示上传按钮 showRemove : true,   //显示移除按钮 showPreview : true,   //是否显示预览 showCaption: false,  //是否显示标题 browseClass: "btn btn-primary",   //按钮样式 dropZoneEnabled: false,  //是否显示拖拽区域,即是否实现拖拽上传; maxFileCount: 1,   //表示允许同时上传的最大文件个数 // maxImageWidth: 800,  //图片的最大宽度 // maxImageHeight: 600,  //图片的最大高度 enctype: 'multipart/form-data',  // 类型 validateInitialCount:true,  // 是否校验数量 previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!", }).on('filebatchuploadsuccess', function(event, data, previewId, index) { // 接口调用完毕后的处理; if("-1" == data.response.code) {  // code是后端返回的状态值; $(".file-error-message").html(data.response.msg); // msg是后端返回的信息 $(".file-error-message").css("display", "block"); }else if("0" == data.response.code){ // 状态值为0,表示上传成功, var path = data.response.msg; // 将返回的路径 $("."+id).text(path);        // 赋值到上面的p标签中,用来显示上传后的路径; alert("上传成功!");          // 提示上传成功了; $("#attachUploadModal").modal('hide');    // 将模态框关闭; } }).on('fileuploaded', function(event, data, previewId, index) { // 这个和上面的类似,每次上传时,有时走这个,有时走上面那个,不知道为什么,还没有搞明白,所以就都写上了 if("-1" == data.response.code) { $(".file-error-message").html(data.response.msg); $(".file-error-message").css("display", "block"); }else if("0" == data.response.code){ var path = data.response.msg; $("."+id).text(path); alert("上传成功!"); $("#attachUploadModal").modal('hide'); } }); $("#attachUploadModal").modal(); } // 用来上传文件的模态框 <div class="modal fade" id="attachUploadModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> <h4 class="modal-title" id="myUploadTitle">动态title</h4> // 这个是动态生成的 </div> <div class="modal-body" id="uploadBody"> <p>内容体</p> </div> </div> </div> </div>

  

3、后端代码: 

注意事项:后端@RequestParam("file") MultipartFile imageFile 中的file一定要写上,不然文件是无法传到后端的,这个坑了我好久。。。。

/**
	 * 单文件上传,返回保存的路径
	 */
	@RequestMapping(value="/file/fileUpload")
	@ResponseBody
	public Result fileUploadSingle(HttpServletRequest request, Model model,@RequestParam("file") MultipartFile imageFile){
		String filePath = saveFile(imageFile);
		Result result = ResultUtil.success(filePath);
		System.out.println(filePath);
		return result;
	}

	/**
	 * 将上传文件保存至指定目录
	 */
	private String saveFile(MultipartFile file) {
		// 判断文件是否为空
		if (!file.isEmpty()) {
			try {
				Date date = new Date();
				String filename = file.getOriginalFilename();
				String currentTimeMillis = String.valueOf(System.currentTimeMillis());
				SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
				String filePartUrl = format.format(date) +  "/"	+ currentTimeMillis+"/"+filename;
				String fileUrl = IMIS_FILE_PATH + filePartUrl;  // 具体的存储路径,这个可自定义;
				File saveDir = new File(fileUrl);
				if (!saveDir.getParentFile().exists()) {
					saveDir.getParentFile().mkdirs();
				}
				// 转存文件
				file.transferTo(saveDir);
				return filePartUrl;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}

  

  

 

posted on 2021-12-14 19:55  Miracle_Jerry  阅读(131)  评论(0)    收藏  举报