Springboot 实现简单的文件上传

Springboot 实现文件上传

1.html

	<button type="button"  οnclick="upload()" id="uploadBtn" class="a-upload mr10" ><i class="layui-icon"></i>上传文件     </button>
	<a href="javascript:;" id="upload"  class="a-upload mr10"><input type="file" name="file" id="file">选择文件</a>

2.js

	function upload() {
				var formData = new FormData();
				formData.append("file",$('#file')[0].files[0])
				$.ajax({
					url: "填写后端的url",
					mimeType:"multipart/form-data",
					data: formData,
					type: "Post",
					dataType: "json",
					cache: false,//上传文件无需缓存
					processData: false,//用于对data参数进行序列化处理 这里必须false
					contentType: false, //必须
					success: function (result) {
						if (result.code==0){
							layer.msg("上传成功");
							//推迟两秒刷新页面
						    setTimeout(function (){window.location.reload()}, 2000);
							// window.location.reload(); //刷新页面
						}
						if(result.code==500){
							layer.msg(result.msg);
						}
					        console.log(result);
					},
				})

			}

3.后端controller层代码

     @PostMapping("fileUpload")
     @ResponseBody
     public AjaxResult fileUpload(@RequestParam("file") MultipartFile file){
         // 获取文件名
         String fileName = file.getOriginalFilename();
         //判断是否为IE浏览器的文件名,IE浏览器下文件名会带有盘符信息
         int unixSep = fileName.lastIndexOf('/');
         // 检查windows样式的路径
         int winSep = fileName.lastIndexOf('\\');
        
         int pos = (Math.max(winSep, unixSep));
         if (pos != -1)  {
             fileName = fileName.substring(pos + 1);
         }
         // 判断是否存在同名文件
         if (existsFile(fileName)) {
             return error("存在同名文件,请先删除原有文件再次上传");
         }
         //FILE_DIR 存放文件地址
         File outFile = new File(FILE_DIR());
         if (!outFile.exists()) {
             outFile.mkdirs();
         }
          log.info("上传路径======"+FILE_DIR()+ fileName);
             try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(FILE_DIR() + fileName)) {
                 StreamUtils.copy(in, out);
                 out.close();
                 in.close();
                 return success("文件上传成功");
             } catch (IOException e) {
                 logger.error("文件上传失败", e);
                 return error("文件上传失败");
             }
     }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值