文件上傳(MultipartFile)


采用springmvc框架實現上傳

jar包支持

 

springMVC配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

        <context:component-scan base-package="com.atguigu"></context:component-scan>
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/view/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
        
        <!--
        靜態資源需要默認的servlet來處理
          -->
        <mvc:default-servlet-handler/>
        <mvc:annotation-driven></mvc:annotation-driven>
        
        <!-- 
        id為固定的,只能為multipartResolver
        作用:將客戶端上傳的file對象轉換成MultipartFile對象,
        設置文件解析的編碼一定要與頁面編碼保持一致pageEncoding
        xml的屬性是純文本,不能寫運算符,屬性
         -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="UTF-8"></property>
            <property name="maxUploadSize" value="888888888"></property>
        </bean>
</beans>

 

1. file.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>測試上傳與下載</title>
</head>
<body>

<a href="down">down</a>
    <form action="up" method="post" enctype="multipart/form-data">
        頭像 :<input type="file" name="uploadFile">
        描述 :<input type="text" name="desc">
        <input type="submit" value="上傳">
    
    </form>
</body>
</html>

2.UploadController

package com.atguigu.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadAndDown {
    @RequestMapping("/down")
    public ResponseEntity<byte[]> down(HttpSession session) throws Exception{
        //獲取下載文件的路徑 (獲取tomcat服務器的位置)
        String realPath = session.getServletContext().getRealPath("img");
        String finalPath = realPath+ File.separator +"1.jpg";
        //創建字節輸入流
        InputStream in = new FileInputStream(finalPath);
        //available():獲取輸入流所讀取的文件的最大字節數
        byte[] body = new byte[in.available()];
        //把字節讀取到數組中
        in.read(body);
        //設置請求頭
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=aaa.jpg");
        //設置響應狀態
        HttpStatus statusCode = HttpStatus.OK;
        in.close();

        
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
        
    }
    
    @RequestMapping(value="/up_old", method = RequestMethod.POST)
    public String up_old (String desc,MultipartFile uploadFile,HttpSession session) throws Exception {
        //獲取上傳文件的名稱
        String fileName = uploadFile.getOriginalFilename();
        //獲取上傳文件的路徑
        String path = session.getServletContext().getRealPath("photo")+File.separator+fileName;
        //獲取輸入流
        InputStream is = uploadFile.getInputStream();
        //獲取輸出流
        OutputStream os = new FileOutputStream(new File(path));
        //開始復制
        int i = 0;
        byte[] bytes = new byte[1024];
        while((i = is.read(bytes))!=-1) {
            os.write(bytes, 0, i);
        }
        os.close();
        is.close();
        return "success";
        
    }
    
    

/**
    寫法二
* 使用springmvc實現上傳,采用MultipartFile的transfer() * @param desc * @param uploadFile * @param session * @return * @throws Exception */ @RequestMapping(value="/up", method = RequestMethod.POST) public String up (String desc,MultipartFile uploadFile,HttpSession session) throws Exception { //獲取上傳文件的名稱 String fileName = uploadFile.getOriginalFilename(); //解決文件重名問題 String finalFileName = UUID.randomUUID().toString()+fileName.substring(fileName.lastIndexOf(".")); //獲取上傳文件的路徑 String path = session.getServletContext().getRealPath("photo")+File.separator+finalFileName; uploadFile.transferTo(new File(path)); return "success"; } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM