上传:
package text.mvc._05_upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletContext;
import java.io.File;
import java.util.Date;
/**
* Created by thinkpad on 2019/9/9.
*/
@Controller
public class UploadController {
@Autowired
private ServletContext servletContext;
@RequestMapping("/save")
public ModelAndView save(MultipartFile file,String username) throws Exception{
//把文件对象,以流的方式写出到img的文件夹中
String realpath = servletContext.getRealPath("/img");
//创建保存到服务器的文件的路径
String path= realpath +"/"+ new Date().getTime() + file.getOriginalFilename();
//新文件对象
File newFile = new File(path);
//使用字节流输出新的文件
file.transferTo(newFile);
return null;
}
}
下载:
package text.mvc._05_upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.Files;
import java.nio.file.Paths;
import static java.nio.file.Paths.*;
/**
* Created by thinkpad on 2019/9/9.
*/
@Controller
public class DownloadController {
@Autowired
private ServletContext context;
@RequestMapping("/download")
public ModelAndView download(String name, HttpServletResponse response) throws Exception{
//设置响应方式为下载
response.setContentType("application/x-msdownload");
//设置响应头,并给下载后的文件取名
response.setHeader("Content-Disposition","attachment;filename="+name);
//把文件对象,以流的方式写出到img的文件夹中
String realpath = context.getRealPath("/img");
//获取具体的文件,并输入到浏览器(下载)
Files.copy(Paths.get(realpath,name),response.getOutputStream());
return null;
}
}