java项目开发-文件上传

2022/7/14 14:54:39

本文主要是介绍java项目开发-文件上传,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

SpringMVC上传文件
1.前端页面设计
文件上传的控件是:,必须以POST方式提交表单,且必须配置enctype="multipart/form-data";
<form action="upload.do" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit"> </form>
2.添加依赖
基于commons-fileupload

commons-fileupload
commons-fileupload
1.3.1

3.在spring配置文件中添加配置:
配置CommonsMultipartReslover
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
在这也可以配置其他属性,如long maxUploadSizePerFile :单个文件最大大小;long maxUploadSize:最大上传大小...
4.创建控制器处理上传

`@Controller
public class UploadController {
//处理上传功能请求的方法
@PostMapping("/upload.do")
@ResponseBody
public String handleUpload(HttpServletRequest request,@RequestParam("file") CommonsMultipartFile file) throws IllegalStateException, IOException {
boolean isEmpty = file.isEmpty();//判断上传文件是否为空
System.out.println(isEmpty);
//确定存储文件夹
String parsePath = request.getServletContext().getRealPath("upload");
File parse = new File(parsePath);
if (!parse.exists()) {
parse.mkdirs();
}
//确定获取的文件名
String originalFilename = file.getOriginalFilename();
//获取相关数据-文件大小
long size = file.getSize();
System.out.println("size:"+size);

	String contentType = file.getContentType();
	System.out.println("contentType:"+contentType);
	List<String> allow = new ArrayList<String>();
	allow.add("image/jpeg");
	allow.add("image/png");
	boolean isAllow=allow.contains(contentType);
	//获取扩展名
	int beginIndex = originalFilename.lastIndexOf(".");
	String suffix = originalFilename.substring(beginIndex);
	String fileName = System.currentTimeMillis()+suffix;
	File dest = new File(parse, fileName);
	**//保存文件**
	file.transferTo(dest);
	return "ok";
}

}`

转:https://blog.csdn.net/Shangxingya/article/details/109562739



这篇关于java项目开发-文件上传的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程