文件上传与下载

package com.qf.controller;

import com.qf.entity.Book;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/*
接收页面中传递过来的文件类型,定义MultipartFile类型参数


 */

@Controller
@RequestMapping("/upload")
public class BookUploadController {
    @RequestMapping("add")
    public String addBook(Book book, MultipartFile picture) throws IOException {
        //添加操作
        //上传图片
        //获取上传文件名
        String filename = picture.getOriginalFilename();
        //处理文件上传后同名问题
        String newString = UUID.randomUUID().toString().replace("-", "") + filename.substring(filename.lastIndexOf("."));
        //构建上传路径
        String path="F:\\pathpng\\"+newString;
        picture.transferTo(new File(path));
        book.setPic(newString);
        System.out.println(book);
        return "/success.jsp";
    }

    @RequestMapping("download")
    public void downLoadFile(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {

        String realPath = request.getServletContext().getRealPath("/img");
        //拼接文件的下载路径
        String path=realPath+"\\"+fileName;
//        设置响应头,
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
//        PrintWriter writer = response.getWriter();
//        ServletOutputStream outputStream = response.getOutputStream();
        //下载操作
        IOUtils.copy(new FileInputStream(path),response.getOutputStream());

    }


}

需要导入的依赖


    <dependency>
      <groupId>commons-iogroupId>
      <artifactId>commons-ioartifactId>
      <version>2.4version>
    dependency>

    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.3.3version>
    dependency>

xml


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

        <property name="maxInMemorySize" value="10485760"/>

    bean>

提醒

MVC视图解析器,重定向不走,只有转发走视图解析器.

你可能感兴趣的:(SpringMVC,spring,boot)