java实现文件上传下载功能
作者:wh456413 发布时间:2021-11-26 17:19:05
标签:java,上传,下载
本文实例为大家分享了java实现文件上传下载的具体代码,供大家参考,具体内容如下
1.上传单个文件
Controller控制层
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("testup")
public class UploadController {
private static Logger LG= LoggerFactory.getLogger(UploadController.class);
/**
* 9.①单个文件上传
* @param file
* @param redirectAttributes
* @return
*/
@RequestMapping(value="/upload",method=RequestMethod.POST,consumes="multipart/form-data")
public String uploadFile(@RequestParam MultipartFile file,RedirectAttributes redirectAttributes){
if(file.isEmpty()){
redirectAttributes.addFlashAttribute("message", "Plse select file");
return "redirect:/test/index";
}
try {
String fileName=file.getOriginalFilename();
/*上传文件存储位置*/
String destFileName="D:\\whupload"+File.separator+fileName;
File destFile=new File(destFileName);
file.transferTo(destFile);
//文件上传成功显示
//redirectAttributes.addAttribute("message","upload file success.");
redirectAttributes.addFlashAttribute("message", "upload file success.");
} catch (Exception e) {
//文件上传失败显示
redirectAttributes.addFlashAttribute("message", "upload file fail");
LG.debug(e.getMessage());
}
return "redirect:/test/index";
}
}
前端页面源码
<p>上传文件,使用multipart/form-data类型</p>
<form action="/testup/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">上传</button>
</form>
2.上传多个文件
Controller控制层
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("testup")
public class UploadController {
private static Logger LG= LoggerFactory.getLogger(UploadController.class);
/**
* 9.②多个文件上传
*/
@RequestMapping(value="/uploadBatchFile",method=RequestMethod.POST,consumes="multipart/form-data")
public String uploadBatchFile(@RequestParam MultipartFile[] files,RedirectAttributes redirectAttributes){
boolean isEmpty=true;
try {
for (MultipartFile multipartFile : files) {
if(multipartFile.isEmpty()){
continue;
}
String fileName=multipartFile.getOriginalFilename();
String destFileName="D:\\whupload"+File.separator+fileName;
File destFile=new File(destFileName);
multipartFile.transferTo(destFile);
isEmpty=false;
}
//int i=1/0;
//localhost:8086/test/index?message=upload file success
//redirectAttributes.addAttribute("message","upload file success.");
} catch (Exception e) {
// TODO Auto-generated catch block
redirectAttributes.addFlashAttribute("message", "upload file fail");
LG.debug(e.getMessage());
return "redirect:/test/index";
}
if(isEmpty){
redirectAttributes.addFlashAttribute("message", "Plse select file");
}else{
redirectAttributes.addFlashAttribute("message", "upload file success.");
}
return "redirect:/test/index";
}
}
前端页面源码
<form action="/testup/uploadBatchFile" method="post" enctype="multipart/form-data">
<input type="file" name="files">
<input type="file" name="files">
<button type="submit">上传</button>
</form>
3.下载文件
Controller控制器
import java.io.File;
import java.net.MalformedURLException;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("testup")
public class UploadController {
private static Logger LG= LoggerFactory.getLogger(UploadController.class);
/**
* 10.下载文件
*/
@RequestMapping("/download")
@ResponseBody
public ResponseEntity<Resource> downloadFile(@RequestParam String fileName){
try {
Resource resource=new UrlResource(
//拼接下载的文件的原路径
Paths.get("D:/whupload"+File.separator+fileName).toUri());
if(resource.exists() && resource.isReadable()){
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
.header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=\""+
resource.getFilename()+"\"").body(resource);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
LG.debug(e.getMessage());
}
return null;
}
}
前端页面源码
<p>下载文件,这里设置默认下载文件为Demo.txt,fileName是下载文件名</p>
<a href="/testup/download?fileName=Demo.txt" rel="external nofollow" >download file</a>
运行效果
最后,需要注意的是,文件上传有默认的大小限制
在配置文件中加入,即可消除限制
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1
来源:https://blog.csdn.net/wh456413/article/details/107302180


猜你喜欢
- package com.yswc.dao.sign;import java.io.BufferedReader;import java.io
- Android ListView的优化,在做Android项目的时候,在用到ListView 界面及数据显示,这个时候如果资源过大,对项目来
- 注解注解定义Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。Java 语言中的类、方法、变
- 本文实例讲述了C# TreeView无限目录树实现方法。分享给大家供大家参考,具体如下:#region 绑定客户树protected voi
- Gson是一个Java库,用来实现Json和Java对象之间的相互转换。Gson是一个托管在https://github.com/googl
- 开发过程, 我们习惯把数据源配置, 项目常量, 日志配置等基础数据配置写到一个个单独的的文件中. 如jdbc.properties等各种.格
- 本文实例讲述了java实现图片裁切的工具类。分享给大家供大家参考,具体如下:package com.yanek.util;import ja
- 本文实例为大家分享了Android实现滑动开关效果的具体代码,供大家参考,具体内容如下自定义开关控件Android自定义控件一般有三种方式
- 本文实例为大家分享了Java实现图形界面计算器的具体代码,供大家参考,具体内容如下 代码:import javax.swing.*
- Android MediaPlayer实现音乐播放器1、布局文件<?xml version="1.0" encod
- 前段时间接到一个Web应用自动生成Word的需求,现整理了下一些关键步骤拿来分享一下。思路:(注:这里只针对WORD2003版本,其它版本大
- 本文实例讲述了java使用Hashtable过滤数组中重复值的方法。分享给大家供大家参考,具体如下:package org.eline.co
- 父类空间优先于子类对象产生在每次创建子类对象时,先初始化父类空间,再创建其子类对象本身。目的在于子类对象中包含了其对应的父类空间,便可以包含
- 第一种方法:一、测试如下,直接设置小圆点不是图标二、准备工作1.在drawable创建dot.xml,设置小圆点,比较方便<?xml
- 本文实例讲述了C#图像处理之边缘检测(Sobel)的方法。分享给大家供大家参考。具体如下://定义sobel算子函数private stat
- 前言这篇文章的内容基于对Spring Security 认证流程的理解,如果你不了解,可以读一下这篇文章:Spring Security 认
- 1.背景由于公司的日志系统使用的是plumelog,最近生产环境老是报 jedis连接池不够,导致丢失日志,而且服务老是重启,怀疑跟日志系统
- 前言在Android开发过程中,Bitmap往往会给开发者带来一些困扰,因为对Bitmap操作不慎,就容易造成OOM(Java.lang.O
- 简介说明本文用实例介绍stream的使用。JDK8新增了Stream(流操作) 处理集合的数据,可执行查找、过滤和映射数据等操作。使用Str
- 本文重在实现理解,过滤器,业务,逻辑需求,样式请无视。。项目结构如下1.idea新建Spring boot项目,在pom中加上thymele