发布于2021-05-29 21:45 阅读(1068) 评论(0) 点赞(30) 收藏(1)
以前用ssm做文件上传,我们通常先要添加依赖,用古老的方法实现文件上传,springboot中做文件上传,我们什么配置都不用做就可以做文件上传的功能。
springboot默认用StandarServletMultipartResolver来实现,要注意tomcat的版本不能过低!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
package com.wangze.studybootweb.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @author: 王泽
*/
@RestController
public class UpdateController {
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/"); //注意格式,/是目录路径例如:/2021/5/25
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest req){ //注意第一个参数文件名,要与前端的一一对应!
//保存到临时目录中
String realPath = req.getServletContext().getRealPath("/");
//分类处理,最终目录
final String format = sdf.format(new Date());
final String path = realPath + format;
//目录可能不存在,用file对象,把路径传入
File folder=new File(path);
//判断是否存在
if(!folder.exists()){
folder.mkdirs(); //创建多层
}
//文件名
final String oldName = file.getOriginalFilename();
final String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
try {
file.transferTo(new File(folder,newName));
//文件保存成功,生成文件访问路径
final String s = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName;
return s;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
常用大小限制的配置
思路:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js">
</script>
</head>
<body>
<div id="result"></div>
<input type="file" id="file">
<input type="button" value="上传" onclick="uploadFile()">
<script>
function uploadFile(){
var formDate = $("#file")[0].files[0];
var formDate =new formDate;
formDate.append("file",file);
$.ajax({
type:'post',
url:'/upload',
processData: false,
contentType: false,
data:formDate,
success:function (msg){
$("#result").html(msg);
}
})
}
</script>
</body>
</html>
作者:以天使的名义
链接:http://www.javaheidong.com/blog/article/207563/b20561355fca5e2985b6/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!