文件上传-pubsec-文件上传大小限制

Caused by: java.lang.IllegalArgumentException: ContextPath must start with '/' and not end with '/'
错误代码:
server:
servlet:
context-path: mozq
原因:不能以斜杠开头,也不能以斜杠结尾。
# 以斜杠开头的路径表示绝对路径和域名端口号直接拼接。
<form method="post" action="/file/upload" enctype="multipart/form-data">
<input type="file" name="userImg">
<input type="submit" value="提交">
</form>
实际请求的路径:http://localhost:8080/file/upload 报错。
项目contextPath=/mozq
代码:
@RestController
@RequestMapping("/file")
public class FileController {
@RequestMapping("/upload")
public Map<String, Object> upload(MultipartFile file){
return null;
}
}
方案:
action="file/upload" 不以斜杠开头。使用相对路径。
org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (62488249) exceeds the configured maximum (10485760)
原因:上传文件大小超过限制。 @Configuration
public class MultiPartConfig {
/**
* 文件上传配置
* @return
*/
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 单个数据大小
factory.setMaxFileSize(DataSize.of(100, DataUnit.MEGABYTES));
/// 总上传数据大小
factory.setMaxRequestSize(DataSize.of(300, DataUnit.MEGABYTES));
return factory.createMultipartConfig();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery.js"></script>
<style>
.hide{
display: none;
}
.tip{
color: red;
font-size: 12px;
}
</style>
</head>
<body> <form id="submitForm">
秘钥文件:<input id="secFile" name="secFile" type="file" onclick="hide('secFile')"><br/>
<div id="secFileCheck" class="hide tip">请选择密钥文件</div>
公钥文件:<input id="pubFile" name="pubFile" type="file" onclick="hide('pubFile')"><br/>
<div id="pubFileCheck" class="hide tip" >请选择公钥文件</div>
密码:<input name="password" type="text" onblur="checkPassword()" onclick="hide('password')"><br/>
<div id="passwordCheck" class="hide tip">请输入密码</div>
<input value="提交" type="button" onclick="submitForm()" ><br/>
</form> <script> function submitForm() { var pubFile = document.getElementById("pubFile").files[0];
var secFile = document.getElementById("secFile").files[0];
var password = $("input[name='password']").val();
console.log("私钥文件:");
console.log(secFile);
console.log("公钥文件:");
console.log(pubFile);
console.log("私钥文件密码:" + password); if(checkFile("pubFile") & checkFile("secFile") & checkPassword()){
var formData = new FormData();
formData.append("pubFile", pubFile);
formData.append("secFile", secFile);
formData.append("password", password); $.ajax({
url: "isPubAndSecretMatch",
type: "post",
data: formData,
contentType: false,
processData: false,
mimeType: "multipart/form-data",
success: function (data) {
console.log("响应数据:" + data);
data = JSON.parse(data);
if(data.flag == "success"){
alert("公钥和私钥匹配成功");
}else if(data.flag == "fail"){
alert(data.message);
}
}
})
}
} function hide(ele) {
$("#" + ele + "Check").addClass("hide");
} function checkFile(fileEleId) {
var fileEle = document.getElementById(fileEleId).files[0];
if(fileEle == null){
$("#" + fileEleId + "Check").removeClass("hide");
return false
}else{
return true;
}
} function checkPassword() {
var password = $("input[name='password']").val();
if(password == null || password==''){
$("#passwordCheck").removeClass("hide");
return false;
}else{
return true;
}
}
</script>
</body>
</html>
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile; /**
* Service class for managing users.
*/
@Service
@Transactional
public class FileService {
/***
* 上传
* @param message 记录消息
* @param inputStream 文件流
*/
public HashMap<String, Object> uploadQRCode(HttpServletRequest request,MultipartFile file,String path) { // 检查文件是否上传过 上传成功文件名规则:用户单位_上传文件名称
HashMap<String, Object> uploadResult = new HashMap<String, Object>();
String realPath = request.getServletContext().getRealPath(path);
System.out.println("上传的path:"+realPath);
File temp = new File(realPath);
// 文件夹check
if (!temp.getParentFile().exists() && !temp.getParentFile().isDirectory()) {
temp.getParentFile().mkdirs();
}
try {
// 成功转存数据文件
file.transferTo(temp);
uploadResult.put("QRCodePath", path);
uploadResult.put("success", true);
uploadResult.put("msg", "上传成功");
} catch (Exception e) {
uploadResult.put("success", false);
uploadResult.put("msg", "上传失败:" + e.getMessage());
e.printStackTrace();
} temp = null;
return uploadResult;
} /***
* 上传
* @param message 记录消息
* @param inputStream 文件流
*/
public Map<String, String> uploadFile(HttpServletRequest request,MultipartFile file,String path) {
// 检查文件是否上传过 上传成功文件名规则:用户单位_上传文件名称
Map<String, String> map= new HashMap<String, String>();
String webpath=path+"/"+ file.getOriginalFilename();
String realPath = request.getServletContext().getRealPath(webpath);
File temp = new File(realPath);
// 文件夹check
if (!temp.getParentFile().exists() && !temp.getParentFile().isDirectory()) {
temp.getParentFile().mkdirs();
}
try {
// 成功转存数据文件
file.transferTo(temp);
map.put("success", "上传成功");
} catch (Exception e) {
map.put("fail", "上传失败:" + e.getMessage());
e.printStackTrace();
}
map.put("webpath", webpath);
temp = null;
return map;
} /***
* 下载
*
*/
public String downLoad(HttpServletRequest request,HttpServletResponse response,String path){
String realPath = request.getServletContext().getRealPath(path);
File file = new File(realPath);
if(file.exists()){ //判断文件父目录是否存在
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition","attachment;fileName=" + file.getName());// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
} public Map<String, String> uploadFilePic(HttpServletRequest request,MultipartFile file,String path) {
// 检查文件是否上传过 上传成功文件名规则:用户单位_上传文件名称
Map<String, String> map= new HashMap<String, String>();
String realPath = request.getServletContext().getRealPath(path);
File temp = new File(realPath);
// 文件夹check
if (!temp.getParentFile().exists() && !temp.getParentFile().isDirectory()) {
temp.getParentFile().mkdirs();
}
try {
// 成功转存数据文件
file.transferTo(temp);
map.put("success", "上传成功");
} catch (Exception e) {
map.put("fail", "上传失败:" + e.getMessage());
e.printStackTrace();
}
map.put("webpath", path);
temp = null;
return map;
}
}

import java.io.IOException;
import java.util.Map; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest; import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; @Controller
@RequestMapping("/upload")
public class FileUploadController {
private static Logger log = LogManager.getLogger(FileUploadController.class);
private static final String PathRoot = "SystemFile/upload/img";
@Resource
private FileService fileService; @RequestMapping("/save")
@ResponseBody
public Map<String, String> uploadFile(@RequestParam("file")MultipartFile file,@RequestParam("xxmc")String xxmc, HttpServletRequest request)
throws IllegalStateException, IOException {
log.info("===========进入文件上传方法===============");
if(!file.isEmpty())
{
Map<String, String> map=fileService.uploadFile(request,file,PathRoot+"/"+xxmc);
return map;
}
return null;
} }

最新文章

  1. 网络编程——URL编程
  2. BZOJ 1113: [Poi2008]海报PLA
  3. (转)Ratchet教程:Buttons组件
  4. sql2008 将行转为字符串, 将字符串转为行 互转
  5. android 组件设置屏幕大小
  6. Java 理论与实践: 用弱引用堵住内存泄漏---转载
  7. [转]MySQL 5.6 全局事务 ID(GTID)实现原理(一)
  8. Hibernate、批量操作数据
  9. asp.net mvc 下载文件 txt doc xsl 等等
  10. mybatis操作动态表+动态字段+存储过程
  11. diff
  12. 网站开发进阶(十八)js获取html标签中的值
  13. Salesforce 自定义标签在代码中的应用
  14. php7函数,声明,返回值等新特性介绍
  15. Java Web之验证码
  16. Tornado学习笔记(一) helloword/多进程/启动参数
  17. Set集合中的treeSet问题:cannot be cast to java.lang.Comparable;
  18. win10下切换多个jdk版本
  19. Ubuntu中Redis的安装与使用
  20. Linux下逻辑地址-线性地址-物理地址图解(转)

热门文章

  1. ubuntu下的mv命令
  2. React、Vue、Angular对比 ---- 介绍及优缺点
  3. 提高python运行效率-pypy
  4. x2
  5. 聊一下,前后分离后带来的跨域访问和cookie问题
  6. php json_decode无法处理\解决方法
  7. php imagemagick 翻译目录
  8. python 自定义Iterator对象
  9. 转 让FPGA替代GPU的6大顾虑,你确定不看看吗?
  10. Ext.NET-WebForm之TreePanel组件