上传下载文件
2021-03-05 21:32
标签:前端 sub Servle indexof coder puts exists def length 上传下载文件 标签:前端 sub Servle indexof coder puts exists def length 原文地址:https://www.cnblogs.com/wsxultimate/p/12902489.html上传下载文件
依赖
上传 方式一(原生)
//判断上传文件是普通表单还是带文件的表单
if(!ServletFileUpload.isMultipartContent(request)){
return;
}
//创建上传的保存路径 如果不存在则创建
String filePath = this.getServletContext().getRealPath("/WEB-INF/upload");
File uploadFile = new File(filePath);
if(!uploadFile.exists()){
uploadFile.mkdir();
}
//缓存,临时文件
//临时路径,进入超过了预期大小,放到零时文件中,过几天删除,或提醒用户转存为永久
String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp");
File tempFile = new File(tempPath);
if(!tempFile.exists()){
tempFile.mkdir();
}
//处理上传文件,一般需要通过流来获取,我们可以使用request。getInputStream()原生态上传流获取,很麻烦
//但是我们都建议使用apache的文件上传来实现,common-fileupload,需依赖common-io组件
DiskFileItemFactory factory = getDiskFileItemFactory(tempFile);
ServletFileUpload upload = null;
try {
upload = getServletFileUpload(factory,request);
} catch (FileUploadException e) {
e.printStackTrace();
}
try {
String msg = uploadParseRequest(request, upload, filePath);
request.setAttribute("msg",msg);
request.getRequestDispatcher("info.jsp").forward(request,response);
} catch (Exception e) {
e.printStackTrace();
}
public DiskFileItemFactory getDiskFileItemFactory(File file){
//1.创建DiskFileItemFactory对象,处理文件上传路径或者大小限制
DiskFileItemFactory factory = new DiskFileItemFactory();
//下面的两行代码有默认值,非必须
//通过这个工厂设置缓冲区,当上传文件大于这个缓冲区的时候,将她放在临时文件中。
factory.setSizeThreshold(1024*1024);//大小为1M
factory.setRepository(file);//临时目录的保存目录,需要一个tempFile
return factory;
}
public ServletFileUpload getServletFileUpload(DiskFileItemFactory factory,HttpServletRequest request) throws FileUploadException {
//2.获取ServletUpload
ServletFileUpload upload = new ServletFileUpload(factory);
//监听上传进度
//可以用来做进度条
//下面七行代码非必须
//判断大小
List
public String uploadParseRequest(HttpServletRequest request,ServletFileUpload upload,String filePath) throws Exception {
String msg = "";
List
方式二 (配置版)
在application-context.xml中配置
方式一
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//获取文件名 : file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,直接回到首页!
if ("".equals(uploadFileName)) {
return "../../index";
}
System.out.println("上传文件名 : " + uploadFileName);
//上传路径保存设置
String path = request.getSession().getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
System.out.println("上传文件保存地址:" + realPath);
InputStream is = file.getInputStream(); //文件输入流
OutputStream os = new FileOutputStream(new File(realPath, uploadFileName)); //文件输出流读取写出
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
os.flush();
}
os.close();
is.close();
return "../../index";
}
方式二 直接新建文件夹 读取并写入
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getSession().getServletContext().getRealPath("/upload");
File realPath = new File(path);
if (!realPath.exists()) {
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:" + realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath + "/" +
file.getOriginalFilename()));
return "../../index";
}
下载文件
@RequestMapping(value = "/download")
public String downloads(HttpServletResponse response, HttpServletRequest
request) throws Exception {
//要下载的图片地址
String path = request.getSession().getServletContext().getRealPath("/upload");
String fileName = "整合.md";
//1、设置response 响应头
response.reset(); //设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符编码
response.setContentType("multipart/form-data"); //二进制传输数据
//设置响应头
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//2、 读取文件--输入流
InputStream input=new FileInputStream(file);
//3、 写出文件--输出流
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//4、执行 写出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
前端
点击下载