导依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
配置最大上传文件大小
spring下:
页面
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
<p><a th:href="@{download/123.jpg}">下载图片</a></p>
上传
package com.qyc.controller;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @author qyc
* @time 2020/4/21 - 17:45
*/
@Controller
public class Upload {
@PostMapping("upload")
public String upload(MultipartFile file) throws IOException {
//文件信息
System.out.println(file.getOriginalFilename()); //文件名
System.out.println(file.getContentType()); //文件类型
System.out.println(file.getSize()); //大小
String realPath = ResourceUtils.getURL("classpath:").getPath()+"/static/file";
String datafile = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
File files = new File(realPath,datafile);
if(!files.exists()) files.mkdirs();
//修改文件名
String newfilename = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+
UUID.randomUUID().toString();
//扩展名
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String filename = newfilename +"."+ extension;
file.transferTo(new File(files,filename));
return "redirect:home";
}
}
下载
package com.qyc.controller;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author qyc
* @time 2020/4/21 - 17:45
*/
@Controller
public class Download {
@GetMapping("/download/{filename}")
public void download(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException {
String realPath = ResourceUtils.getURL("classpath:").getPath()+"static/file";
System.out.println(realPath);
//读取文件
File file = new File(realPath,filename);
//文件输入流
FileInputStream is = new FileInputStream(file);
// 附件下载
response.setHeader("content-disposition","attachment;fileName="+filename);
//文件输出流
ServletOutputStream os = response.getOutputStream();
IOUtils.copy(is,os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
}