web中上传下载就需要使用 apache的包,,
<commons-io.version>2.4</commons-io.version>
<common-fileupload.version>1.3.1</common-fileupload.version>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${common-fileupload.version}</version>
</dependency>
使用maven,灰常方便,,(maven详解)
一。上传文件
前端页面,部分代码
<form method="post" action="/student/upload_file" enctype="multipart/form-data" >
<input type="file" name="file1"><br/>
<input type="file" name="file2"><br/>
<input type="submit" value="提交">
</form>
注意需要设置,enctype=”multipart/form-data”
后台接收代码:
@RequestMapping("/upload_file")
public String uploadFile(MultipartFile file1) throws IOException {
File uploadFile = new File("/" + file1.getOriginalFilename());
//将文件存入相应路径。
file1.transferTo(uploadFile);
return "show";
}
很方便吧,此处只接受了一个文件,接受两个文件可在后面添加相应名称(名称与前端name对应),,出现重名,后台可以使用数组进行接收,,MultipartFile,方便的不能做朋友
二。下载文件
方式一:(有点错误,还未解决),有兴趣可以试试,很尴尬的错误,(多了两个双引号)
@RequestMapping("/download")
public ResponseEntity<byte[]> download() throws IOException {
String path = "/download.txt";
File file = new File(path);
HttpHeaders headers = new HttpHeaders();
String fileName = new String("文本.txt".getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
ResponseEntity <byte[]>,泛型为byte[]时,会出现乱码,
ResponseEntity <String>,泛型为String时,会出两个冒号,文件还是有问题,
方式2,,完美下载,,亲测
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String realPath = "/download.txt";
File file = new File(realPath);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition",
"attachment;fileName=" + "/download.txt");// 设置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
文件上传方式2,亲测完美