java--Spring MVC upload and download files

Spring MVC uploads files and downloads files

The Spring web MVC framework provides a model-view-control architecture and components that can be used to develop flexible, loosely coupled web applications. The MVC pattern leads to the separation of different aspects of the application (input logic, business logic, and UI logic), while providing loose coupling between these elements.



upload files

  • First jspcreate the table in
<form action="/upload.do" method="post" enctype="multipart/form-data">

    <%--上传文件--%>
    请选择文件<input type="file" name="file"><br>
    请选择文件<input type="file" name="file"><br>
    <button>提交</button>
</form>
  • springmvc.xmlInject the file stream in
    <!--注入文件流-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <--上传文件大小-->
        <property name="maxUploadSize" value="10000000"></property>
    </bean>
  • create UploadControllercontroller
package cn.zbw.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

@Controller
public class UploadController {
    
    
    @RequestMapping("/upload.do")
    public String upload(MultipartFile file[], HttpServletRequest request) throws IOException {
    
    
        for (int i = 0; i < file.length; i++) {
    
    
//            上传路径
            String realPath = request.getServletContext().getRealPath("/upload/");
//            获取文件名字
            String name = file[i].getOriginalFilename();
//            修改文件名字
            String newName = new Date().getTime() + new Random().nextInt(9999999) + name;
            File file1 = new File(realPath + newName);
            file[i].transferTo(file1);
        }
        return "success";
    }
}

  • upload successfully return to successthe page
<%--
  Created by IntelliJ IDEA.
  User: 冰冰赵博文
  Date: 2021/03/18
  Time: 上午 11:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>成功页面</title>
</head>
<body>
ok成功上传
</body>
</html>

The result is:
insert image description here
insert image description here
insert image description here
the upload is successful and the file is renamed:
insert image description here



download file

  • create jsppage
<%--下载文档与图片 --%>
<a href="/download/考教分离系统.doc">下载文档</a>
<a href="download.do?fileName=冰冰1.jpg">下载图片</a>

One thing to note here is that you cannot directly write the path when downloading a picture, otherwise you will view the picture but not download it, so you need to find it before downloading.

  • create DownloadControllercontroller

One thing to pay attention to when downloading is to convert the format before transferring UTF-8转换为iso-8859-1, this is a point to remember.

package cn.zbw.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
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 javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Controller
public class DownloadController {
    
    

    @RequestMapping("/download.do")
    public ResponseEntity<byte[]> download(@RequestParam("fileName") String fileName, HttpServletRequest request) throws IOException {
    
    
//        获取下载路径
        String realPath = request.getServletContext().getRealPath("/download/");
        File file = new File(realPath + fileName);
//        转格式
        String newName=new String(fileName.getBytes("UTF-8"), "iso-8859-1");
//        转流
        HttpHeaders hh = new HttpHeaders();
        hh.setContentDispositionFormData("attachment",newName);
        hh.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),hh, HttpStatus.CREATED);
    }
}

The result is:
insert image description here
insert image description here
insert image description here
successfully downloaded


Guess you like

Origin blog.csdn.net/weixin_45686583/article/details/115005230