SpringMVC 文件上傳及下載

首先須要導入jar包java

建立一個jsp頁面web

 

package cn.happy.Controller;

import java.io.File;


import javax.servlet.http.HttpSession;

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

@Controller
public class MyController {
    @RequestMapping(value="/first.do")
    public String doFirst(HttpSession session,MultipartFile uploadfile ) throws Exception{
        if (uploadfile.getSize()>0) {
            //獲取前半部分路徑
            String leftpath=session.getServletContext().getRealPath("/images");
            //獲取文件名稱
            String filename = uploadfile.getOriginalFilename();
            //限制文件類型
            if(filename.endsWith(".jpg")||filename.endsWith(".JPG")){
                    File file=new File(leftpath,filename);
                    uploadfile.transferTo(file);
        
            
            return "WELCOME.jsp";
        }
        }
        
        return "error.jsp";
    }

配置文件:spring

 <!-- 配置包掃描器-->
       <context:component-scan base-package="cn.happy.Controller"></context:component-scan>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>


<mvc:annotation-driven/>

多文件上傳相似於單文件上傳 區別在於:apache

 文件下載:session

import java.io.File;
import java.io.IOException;

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;
@Controller
public class DownFile {
    @RequestMapping(value="/download.do")
     public ResponseEntity<byte[]> download() throws IOException {    
         //圖片真實路徑
            File file=new File("D:\\brotherC.jpg");  
            HttpHeaders headers = new HttpHeaders();    
            String fileName=new String("brotherC.jpg".getBytes("UTF-8"),"iso-8859-1");//爲了解決中文名稱亂碼問題  
            headers.setContentDispositionFormData("attachment", fileName);   
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);    
        }    
    }  
    
相關文章
相關標籤/搜索