前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >javaEE项目Multipartfile实现文件上传下载并解决上传与下载文件中文乱码的问题

javaEE项目Multipartfile实现文件上传下载并解决上传与下载文件中文乱码的问题

作者头像
洋仔聊编程
发布2019-01-15 17:30:55
2.3K0
发布2019-01-15 17:30:55
举报

里面包含了文件上传下载并解决上传与下载文件中文乱码的问题,运用正则表达式判断字符串中是否包含中文和得到一个文件夹下的所有文件的方法,几乎集合了上传下载所需要的所有东西.下面代码加红的部分就是这几个重要点!

知识要大家一起分享嘛.

首先,需要配置好Spring+Springmvc的环境

1.在maven中添加: 如果你不是用maven管理项目的话,就百度Multipartfile所需的jar包即可,然后添加上jar包即可

代码语言:javascript
复制
<!--文件上传下载支持jar包-->

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload</artifactId>

<version>1.3</version>

</dependency>

2.在你配置视图解析器的xml里面添加:

代码语言:javascript
复制
<!-- 定义文件解释器 -->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- 设置默认编码 解决了上传文件名乱码的问题-->

<property name="defaultEncoding" value="utf-8"></property>

<!-- 上传图片最大大小5M-->

<property name="maxUploadSize" value="5242440"></property>

</bean>

2.新建一个测试页面

代码语言:javascript
复制
<%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>文件上传下载</title>

</head>

<body>

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

选择文件:<input type="file" name="file" width="120px">

<input type="submit" value="上传">

</form>

<hr>

<form action="downstudent" method="get">

文件名:<input type="text" name="filename">

<input type="submit" value="下载">

</form>

</body>

</html>

3.新建一个controller页面

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;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

@Controller

public class FileController {

/**

* 前台得到教师上传的文件名 用于学生下载文件

* @param request

* @return

*/

@RequestMapping("/getAllFileStudent")

public File[] GetAllFileNameStudnet(HttpServletRequest request){

//得到路径

String path = request.getSession().getServletContext().getRealPath("importantFile");

File file = new File(path);

//得到该路径下的所有文件的属性

File[] array = file.listFiles();

return array;

}

/**

* 前台得到学生上传的文件名 用于教师下载文件

* @param request

* @return

*/

@RequestMapping("/getAllFileTeacher")

public File[] GetAllFileNameTeacher(HttpServletRequest request){

//得到路径

String path = request.getSession().getServletContext().getRealPath("uploadFile");

File file = new File(path);

File[] array = file.listFiles();

return array;

}

/**

* 学生文件上传功能

* @param file

* @return

* @throws IOException

*/

@RequestMapping(value="/uploadstudent",method= RequestMethod.POST)

@ResponseBody

public String uploadStudent(MultipartFile file, HttpServletRequest request) throws IOException{

//设置路径,该语句会自动的在该项目的target里面的项目名下的目录里面自动创建文件夹uploadFile,用于存放上传文件

String path = request.getSession().getServletContext().getRealPath("uploadFile");

//得到上传文件的文件名

String fileName = file.getOriginalFilename();

//创建文件

File dir = new File(path,fileName);

//判断目录是否存在,如果父目录不存在,调用mkdirs方法创建父目录与子目录

if(!dir.exists()){

dir.mkdirs();

}

//MultipartFile自带的解析文件的方法

file.transferTo(dir);

return "上传文件成功!";

}

/**

* 学生文件下载功能

* @param request

* @param response

* @param file

* @throws Exception

*/

@RequestMapping("/downstudent")

public void downStudent(

HttpServletRequest request,

HttpServletResponse response,

@RequestParam("filename") String file) throws Exception{

//模拟文件,获取文件下载路径,file为需要下载的文件名

String fileName = request.getSession().getServletContext().getRealPath("importantFile")+"/"+file;

//获取输入流

InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));

//运用正则表达式判断文件名是否含有中文字符,进行转码,避免乱码

Pattern p = Pattern.compile("[\u4e00-\u9fa5]");

Matcher m = p.matcher(file);

//判断是否存在 存在进入循环

if (m.find()) {

//转码,避免下载文件时文件名中文乱码

String userAgent = request.getHeader("User-Agent");

byte[] bytes = userAgent.contains("MSIE") ? file.getBytes() : file.getBytes("UTF-8"); // file.getBytes("UTF-8")处理safari的乱码问题

file = new String(bytes, "ISO-8859-1");

}

//设置文件下载头

response.addHeader("Content-Disposition", String.format("attachment;filename=" + file));

//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型

response.setContentType("multipart/form-data");

BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());

int len = 0;

while((len = bis.read()) != -1){

out.write(len);

out.flush();

}

out.close();

}

}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年08月06日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档