SpringMVC中文件的上传

1:首先搭建了一个sprigmvc的环境,在spring的配置文件中添加下面的配置。里面还可以有很多其他的参数。

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的最大尺寸为5MB -->
        <property name="maxUploadSize" value="5242880"/>
        <property name="defaultEncoding" value="utf-8"/>
    </bean>

前台表单页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload" method="post">
        <input type="file" name="file">
        <input type="submit" value="upload">
    </form>
    <hr>
    <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload2" method="post">
        <input type="file" name="file">
        <input type="submit" value="upload">
    </form>
</body>
</html>

controller层

package com.dongmu.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
public class MyController {
    @RequestMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String name = file.getOriginalFilename();
//注意:String getFieldName():获取表单项的name的属性值。
//        System.out.println("上传文件的全部路径:"+name);
        //获取上传文件的文件名
        if (name!=null&&name.length()>0){
//            String uuidPath= UUID.randomUUID().toString();

            String uploadPath = request.getServletContext().getRealPath("/upload");
            /*File uploadFile = new File(uploadPath);
            if (!uploadFile.exists()){
                uploadFile.mkdir();
            }*/

//            String realPath = uploadPath+"/"+uuidPath;
            File realuploadFile = new File(uploadPath);
            if (!realuploadFile.exists()){
                realuploadFile.mkdirs();
            }


            //获得文件的上传流
            InputStream inputStream = file.getInputStream();
            //获取文件的输出流
            FileOutputStream outputStream = new FileOutputStream(new File(realuploadFile,name));

            //创建一个缓冲区
            byte[] bytes = new byte[1024*1024];

            int len = 0;

            while ((len=inputStream.read(bytes))>0){
                outputStream.write(bytes,0,len);
            }

            outputStream.close();
            inputStream.close();

            System.out.println("文件上传成功");

            return "redirect:/index.jsp";
        }else {
            return "redirect:/index.jsp";
        }
    }

    @RequestMapping("/upload2")
    public String upload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String uploadPath = request.getServletContext().getRealPath("/upload");
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()){
            uploadFile.mkdir();
        }
        file.transferTo(new File(uploadFile+"/"+file.getOriginalFilename()));

        return "redirect:/index.jsp";
    }
}

springMVC利用response实现资源的下载

@RequestMapping("/download")
    public void download2(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println(123);
        String realpath = request.getServletContext().getRealPath("/");
        String filename = "壁纸.jpg";
        System.out.println(realpath);
        response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(filename,"utf-8"));
        FileInputStream inputStream = new FileInputStream(realpath+"static/nsn.jpg");
        response.setContentType("multipart/form-data");
        System.out.println(222);
        byte[] bytes = new byte[1024];
        int len =0;
        //用response对象获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        while ((len=inputStream.read(bytes))>0){
            outputStream.write(bytes,0,len);
        }
        System.out.println(333);
        inputStream.close();
        outputStream.close();


    }
要保证自己网站下面的资源目录里面有这个资源,不然会出错。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北海冥鱼未眠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值