了解SpringMVC的上传和下载

springmvc.xml的配置



    
    
    
    
    
    
        
        
        
    

    
    
        
        
        
    

web.xml的配置




    
        dispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
        
            contextConfigLocation
            classpath:*.xml
        
    
    
        dispatcherServlet
        *.do
    
    
        fileEncoding
        org.springframework.web.filter.CharacterEncodingFilter
        
            Encoding
            UTF-8
        
    
    
        fileEncoding
        /*
    

主要代码

package cn.hp.controller;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Random;
@Controller
public class FileUploadController {
    @RequestMapping(value="upload.do")
    public String upload(MultipartFile file[], HttpServletRequest request) throws IOException {
        //1.获取上传文件路径
        String path = request.getServletContext().getRealPath("/upload");
        for (int i =0;i download(@RequestParam("fileName") String fileName,HttpServletRequest request) throws IOException {
        //1.下载路径
        String path = request.getServletContext().getRealPath("/download/");
        //2.实例化File类的对象加载下载的路径和文件
        File f= new File(path+fileName);
        //3.转格式
        String newName = new String(fileName.getBytes("utf-8"),"iso8859-1");
        //4.转流
        HttpHeaders hh = new HttpHeaders();
        hh.setContentDispositionFormData("attachment",newName);
        hh.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //5.相应发送
        return  new ResponseEntity(FileUtils.readFileToByteArray(f),hh, HttpStatus.CREATED);
    }
}

NewFile.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


<%--如果说表单有文件上传的功能,那么表达就要设置这个属性--%>
文件上传
文件上传
文件上传
下载文件 下载文件 下载文件1 下载文件2 下载文件3

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


上传成功


了解SpringMVC的上传和下载_第1张图片

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

你可能感兴趣的:(了解SpringMVC的上传和下载)