第七章、文件上传(一)(SpringBoot2.x)

springboot文件上传 MultipartFile file,源自SpringMVC
MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效)
本案例将图片上传到如下地方:

       

项目结构如下:

JsonData是封装返回的数据

import java.io.Serializable;

public class JsonData implements Serializable{
	private static final long serialVersionUID = 1L;

	//状态码,0表示成功,-1表示失败
	private int code;
	
	//结果
	private Object data;

	//错误描述
	private String msg;

	public JsonData(int code, String msg) {
		super();
		this.code = code;
		this.msg = msg;
	}
	public JsonData(int code, Object data, String msg) {
		super();
		this.code = code;
		this.data = data;
		this.msg = msg;
	}

controller如下:

/**
 * 上传文件
 * @param file
 * @param request
 * @return
 */
@RequestMapping(value = "upload")
@ResponseBody
public JsonData upload(@RequestParam("head_img") MultipartFile file,HttpServletRequest request) {
  
	//file.isEmpty(); 判断图片是否为空
	//file.getSize(); 图片大小进行判断
	
	String name = request.getParameter("name");
	System.out.println("用户名:"+name);
	
	// 获取文件名
	String fileName = file.getOriginalFilename();	        
	System.out.println("上传的文件名为:" + fileName);
	
	// 获取文件的后缀名,比如图片的jpeg,png
	String suffixName = fileName.substring(fileName.lastIndexOf("."));
	System.out.println("上传的后缀名为:" + suffixName);
	
	// 文件上传后的路径
	fileName = UUID.randomUUID() + suffixName;
	System.out.println("转换后的名称:"+fileName);
	
	String filePath = getImagePath(request);
	System.out.println("filePath" + filePath);
	
	File dest = new File(filePath + fileName);
   
	try {
		file.transferTo(dest);
		return new JsonData(0, fileName);
	} catch (IllegalStateException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return  new JsonData(-1, "fail to save ", null);
}



/**
 * 上传文件的保存路径(不含文件名)
 * 存储路径(放在项目中的static/images目录下)
 * @param request
 * @return
 */
private String getImagePath(HttpServletRequest request){
	String projectPath = System.getProperty("user.dir");// E:\workspace\xdclass_spring_boot
	// 返回  E:\workspace\xdclass_spring_boot\src\main\resources\static\images\
	return projectPath + "/src/main/resources/static/images/";
}

通过访问static下面的upload.html静态资源文件,页面显示如下:

选择好上传的文件、输入姓名,点击上传,上传文件成功后显示如下:

msg属性是保存时给图片创建的新文件名,刷新项目文件夹images,可以发现该图片文件

这时可以在浏览器中访问该图片

访问路径 http://localhost:8080/images/129531dd-0eec-4943-ae75-869f1ffada59.jpg

注意:若是在IE浏览器中,会出现文件上传时候请求返回出现文件下载的情况,由于IE不支持Content-Type为application/json格式的返回类型,而上传时候设置请求Content-Type为multipart/form-data; 使用@ResponseBody就会将请求的返回Content-Type为application/json格式

 <form enctype="multipart/form-data" method="post" action="/upload">

在不同的框架中有不同的解决办法,而SpringBoot中的具体的解决方法如下:

package net.xdclass.demo.domain;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {
	
	/**
	 * 解决IE浏览器  @ResponseBody返回json的时候提示下载问题
	 * @return
	 */
	public MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        MediaType media = new MediaType(MediaType.TEXT_HTML, Charset.forName("UTF-8"));
        supportedMediaTypes.add(media);
        jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
        return jsonConverter;
    }
	
	@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(customJackson2HttpMessageConverter());
    }
}

引入一个类即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值