【Spring mvc】处理文件上传的请求

目录

导入依赖

上传文件与测试

        ①通过表单提交

        ②通过Postman工具测试

在控制器中完成上传文件并保存的请求

        ①原始方式

        ②使用Spring提供的方法


导入依赖

<!--文件上传-->

<dependency>

        <groupId>commons-fileupload</groupId>

        <artifactId>commons-fileupload</artifactId>

        <version>1.4</version>

</dependency>

 

<!--工具包-->

<dependency>

        <groupId>commons-io</groupId>

        <artifactId>commons-io</artifactId>

        <version>2.6</version>

</dependency>

上传文件与测试

        上传文件需要的是post请求,因为get请求传输数据的大小最大为2KB,post请求方式要大得多。

①通过表单提交

<form  action="提交页面"  method="post"  enctype="multipart/form-data">

<input type="file" name="接收参数名称">

②通过Postman工具测试

 

  • 选用POST请求方式
  • 参数显示在BODY中(GET请求的内容在请求头中,POST在请求体中)
  • 选择form-data
  • 选择文件
  • 从本地选择需要上传的文件

 

在控制器中完成上传文件并保存的请求

①原始方式

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Controller
@RequestMapping(value="file")
public class FileController{

	@RequestMapping(value="/uploadfile",produces="text/html;charset=utf-8")
	@ResponseBody
    //控制器不是返回页面,而是字符串

	public String uploadTest(@RequestParam("file") MultipartFile file, 
                              HttpServletRequest  request)      
            //MultipartFile是由spring提供的类
					          throws IOException{  
		    //IOException由通过文件创建字节输入流抛出,后续错误交给spring处理
		
		//获取文件名
		String upload Name = file.getOriginalFilename();
		if("".equals(uploadName)){
			//如果用户没有上传文件,就无法得到文件名
			return "你并没有上传文件啊喂";
		}
		
		//获取项目中文件的绝对路径,保存路径值
		String loadPath = request.getServletContext().getRealPath("/upload/");

		//查看路径对应的目录
		File newPath = new File(loadPath);

		//如果此路径不存在,创建此目录
		if(!newPath.exists()){
			newPath.mkdir();
		}

		//生成永不重复的文件名
		//变成字符串,将随机出现的-替换为空字符串
		String uuid = UUID.randomUUID().toString().replace("-","");

		//通过commons-io工具的FilenameUtils类得到上传文件的后缀
		String suffix = FilenameUtils.getExtension(uploadName);

		//保存文件的完整名称
		String fileName = uuid + "." + suffix;

		//文件输入流读取文件
		//需要抛出异常IOException  认为有可能file不存在
		InputStream is = file.getInputStream();

		//文件输出流保存文件到项目中
		//地址为apache-tomcat-9.0.65\\webapps\\ssm\\upload\\
		FileOutputStream os = new FileOutputStream(new File(newPath, fileName));

		int len = 0;
		//缓冲区
		byte[] buffer = new byte[1024];

		//读取数据存入参数数组中,返回读取长度,如果没有内容返回-1
		while((len = is.read(buffer)) != -1){
			//从数组下标为0的位置,写到为len的位置
			os.write(buffer,0,len);
			//清空缓冲区
			os.flush();
		}
		//后用的资源先关闭
		os.close();
		is.close();
		return "文件上传成功,文件名为:" + fileName 
                + ",文件保存位置为:" + loadPath + fileName;
	}

②使用Spring提供的方法

@RequestMapping(value="/upload",produces="text/html;charset=utf-8")
@ResponseBody
public Stringupload(@RequestParam("file") MultipartFile file,HttpServletRequest request)
			     throws IOException{
	//获取文件名
	StringuploadName=file.getOriginalFilename();
	if("".equals(uploadName)){
		return"你并没有上传文件啊喂";
	}
	//保存路径值
	String loadPath = request.getServletContext().getRealPath("/upload/");

	//创建路径对应的目录
	File newPath = newFile(loadPath);

	//如果此路径不存在,创建此目录
	if(!newPath.exists()){
		newPath.mkdir();
	}

	//生成永不重复的文件名
	//变成字符串,将随机出现的-替换为空字符串
	String uuid = UUID.randomUUID().toString().replace("-","");

	//通过commons-io工具的FilenameUtils类得到上传文件的后缀
	String suffix = FilenameUtils.getExtension(uploadName);

	//保存文件的完整名称
	String fileName = uuid + "." + suffix;

	//简化输入输出流的过程
	//将上传的文件转换为指定路径的新文件
	file.transferTo(new File(newPath,fileName));
	return"文件上传成功,文件名为:" + fileName + ",文件保存位置为:" + loadPath + fileName;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值