SpringMVC文件上傳下載

很少說,代碼:html


Spring-config.xml
<!-- spring能夠自動去掃描base-pack下面的包或者子包下面的java文件, 若是掃描到有Spring的相關注解的類,則把這些類註冊爲Spring的bean --> <context:component-scan base-package="org.fkit.controller"></context:component-scan> <!-- 視圖解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/content/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上傳文件的上限(字節) --> <property name="maxUploadSize" value="10485760"/> <!-- 請求編碼格式 --> <property name="defaultEncoding" value="UTF-8"></property> </bean>


package
org.fkit.domain; import java.io.Serializable; import org.springframework.web.multipart.MultipartFile; // 域對象,實現序列化接口,用戶類 public class User implements Serializable{ private String username; private MultipartFile image; public User() { super(); // TODO Auto-generated constructor stub } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public MultipartFile getImage() { return image; } public void setImage(MultipartFile image) { this.image = image; } }
package org.fkit.controller;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.fkit.domain.User;
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.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileUploadController{
    @RequestMapping(value="/{forName}")
    public String ForName(@PathVariable String forName){
        //動態跳轉頁面
        return forName;
    }
    @RequestMapping(value="/register")
    public String register(HttpServletRequest request,@ModelAttribute User user,Model model)
            throws IllegalStateException, IOException{
        System.out.println(user.getUsername());
        if (!user.getImage().isEmpty()) {
            //上傳文件路徑
            String path=request.getServletContext().getRealPath("/images/");
            //文件名
            String fileName=user.getImage().getOriginalFilename();
            File filePath=new File(path,fileName);
            //判斷路徑是否存在,如不存在則建立一個
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            //將上傳文件保存到一個目標文件夾中
            user.getImage().transferTo(new File(path+File.separator+fileName));
            //將用戶添加到model
            model.addAttribute("user",user);
            return "userInfo";
        }else{
            return "errors";
        }
    }
 @RequestMapping(value="/download")
public ResponseEntity<byte[]> download(HttpServletRequest request,@RequestParam("filename") String filename,Model model)throws Exception{ //下載文件的路徑 String path=request.getServletContext().getRealPath("/images/"); File file=new File(path+File.separator+filename); HttpHeaders headers=new HttpHeaders(); //下載文件顯示全名,並解決中文亂碼 的問題 String downloadFileName=new String(filename.getBytes("UTF-8"),"iso-8859-1"); //通知瀏覽器以attachment(下載方式)打開圖片 headers.setContentDispositionFormData("attachment", downloadFileName); //application/octet-streama:二進制流數據(最多見的的文件下載) headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.CREATED); } }
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用戶註冊</title>
</head>
<body>
    <h2>用戶註冊</h2>
    <form action="register" enctype="multipart/form-data" method="post">
        <table>
            <tr>
                <td>用戶名:</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>請上傳頭像:</td>
                <td><input type="file" name="image"></td>
            </tr>
            <tr>
                <td><input type="submit" value="註冊"></td>
            </tr>
        </table>
    </form>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件下載</title>
</head>
<body>
<h3>文件下載</h3>
<a href="download?filename=${requestScope.user.image.originalFilename}">
${requestScope.user.image.originalFilename }
</a>
</body>
</html>

 

springMVC上傳下載至關簡單,很是適用java

相關文章
相關標籤/搜索