springMVC 文件上传和下载

 文件的下载

获得服务器文件的根路径

String realPath=servletContext.getRealPath("/");

realPath:

E:\SpringMVC\Springmvc-project1\Springmvc-demo2\target\Springmvc-demo2-1.0-SNAPSHOT\

获得根路径之后在跟路径后面加上我想创建的层次名和文件名,可以直接这样写:

String realPath=servletContext.getRealPath("/static/img/1.jpg");

realPath:

E:\SpringMVC\Springmvc-project1\Springmvc-demo2\target\Springmvc-demo2-1.0-SNAPSHOT\static\img\1.jpg

@Controller
public class FileUpAndDown {
    @RequestMapping("/download")
    public ResponseEntity<byte[]> downloadfile(HttpSession session)throws IOException
    {
//        获取servletcontext对象(就是application对象,通过它可以读取配置文件,javaweb基础)
        ServletContext servletContext=session.getServletContext();
//        获得要下载文件在服务器中存放的真实地址
        String realPath=servletContext.getRealPath("/static/img/1.jpg");
//        获得文件地址的输入字节流
        InputStream is=new FileInputStream(realPath);
//        获得输入文件的字节流的长度  is.available()代表字节流的长度
        byte[] bytes=new byte[is.available()];
//      将输入流中的数据放到字节数组中
//      bytes就是下载文件的字节流,就是响应体
        is.read(bytes);
//       创建HttpHeaders对象设置响应头信息
        MultiValueMap<String,String> headers=new HttpHeaders();
//        在multivaluemap对象中,设置下载方式(附件形式)            下载的文件名
        headers.add("Content-Disposition","attachment;filename=1.jpg");
//        设置响应状态码
        HttpStatus status=HttpStatus.OK;
//         创建ResponseEntity对象     bytes 文件的字节流也就是响应体,
//         header文件的下载方式,文件临时名称 status 下载状态码,ok表示成功200
        ResponseEntity<byte[]> responseEntity=new ResponseEntity<>(bytes,headers,status);
//        关闭输入流
        is.close();
        return  responseEntity;
    }

文件的上传

1.不能使用get请求,只能使用post请求

2.form表单中必须有  属性enctype="multipart/form-data"  才是以二进制方式传参数
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
上传步骤:
a>添加依赖:

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

b>在SpringMVC的配置文件中添加配置:

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

c>控制器方法:

先把文件要存放在服务器的地址的绝对路径找出来,之后直接 photo.transferTo(file);即可

<form  method="post" enctype="multipart/form-data" th:action="@{/fileupload}" >
    <input type="file" name="photo" id="file1">
    <button type="submit">点我提交</button>
</form>

photo 是input标签 的name 

@RequestMapping("/fileupload")
    @ResponseBody
    public String testfileupload(MultipartFile photo, HttpSession session) {

//        因为如果要上传的文件重名了,则会替换掉原来的文件,所以所有上传到服务器的文件都要重命名一次,
//        新名字随机生成,且后缀是要上传文件的后缀
        String filename = photo.getOriginalFilename();//获得要上传文件的文件名
        String houzhui = filename.substring(filename.lastIndexOf("."));//获得要上传文件的后缀
        String uuid = UUID.randomUUID().toString();
        String newname=uuid+houzhui;
        System.out.println(newname);

//        获得要接收上传的文件的文件夹在服务器的绝对路径  
// ServletContext就是applicationcontext javaweb基础 jsp九大内置对象之一,
//  可以用于读取配置文件,servlet之间共享数据等
        ServletContext context = session.getServletContext();
//        FileUpLoad 会在服务器找这个文件夹,找不到就返回空,找到了就返回该文件夹在服务器的绝对路径
        String filepath=context.getRealPath("bootstrap/FileUpLoad");
        File file=new File(filepath);
//        如果找不到,就在服务器文件夹下创建该文件夹
        if (!file.exists()) {
            file.mkdir();
        }
        String finalpath = file + File.separator + newname;
        System.out.println(filepath);
        System.out.println(finalpath);

//        上传文件
        try {
            photo.transferTo(new File(finalpath));//核心语句,将photo上传到file文件中
        } catch (IOException e) {
            e.printStackTrace();
        }

    return "index" ;
    }

输出 

 target文件夹才是服务器的文件夹,所以上传的文件会存放进这个目录。

这个SpringMvc-1.0-SNASHOT  可能是服务器的跟路径,因为如果没有FileUpLoad文件夹,

会在SpringMvc-1.0-SNASHOT 下根据

context.getRealPath  获得的路径,创建新的FileUpload

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值