欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

第 7 章:文件上传 - 1. 基本上传操作

最编程 2024-06-23 11:51:42
...
开源中国社区团队直播首秀,以分享为名讲述开源中国社区背后的故事”

所有只要与WEB开发牵扯到的开发框架都必须去面对有文件的上传处理,在原始的Spring之中所使用的上传组件 是apache的fileupload组件, 在SpringBoot里面也同样要继续使用此组件。

1、如果要进行上传处理,则首先需要准备出相应的控制器;

package cn.mldn.microboot.controller;

import java.io.IOException;

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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.mldn.microboot.util.controller.AbstractBaseController;

@Controller
public class UploadController extends AbstractBaseController {
	@RequestMapping(value = "/uploadPre", method = RequestMethod.GET)
	public String uploadPre() { // 通过model可以实现内容的传递
		return "upload_page";
	}
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String upload(String name, MultipartFile photo) {
		if (photo != null) {	// 现在有文件上传
			System.out.println("【*** 文件上传 ****】name = " + name);
			System.out.println("【*** 文件上传 ****】photoName = " + photo.getName());
			System.out.println("【*** 文件上传 ****】photoContentType = " + photo.getContentType());
			System.out.println("【*** 文件上传 ****】photoSize = " + photo.getSize());
			try {
				//photo.getInputStream();
				System.out.println("========"+photo.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "upload-file";
	}
}

2、建立一个编辑上传的页面

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<title>SpringBoot模版渲染</title>
	<script type="text/javascript" th:src="@{/js/main.js}"></script> 
	<link rel="icon" type="image/x-icon" href="/images/mldn.ico"/>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
	<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
		姓名:<input type="text" name="name"/><br/>
		照片:<input type="file" name="photo"/><br/>
		<input type="submit" value="上传"/>
	</form>
</body>
</html>

http://localhost/uploadPre

【*** 文件上传 ****】name = 603347175@qq.com
【*** 文件上传 ****】photoName = photo
【*** 文件上传 ****】photoContentType = image/png
【*** 文件上传 ****】photoSize = 200044
========java.io.ByteArrayInputStream@62b601

 

 

此时文件上传的基本操作就成功实现了。

推荐阅读