SpringBoot之MultipartFile文件上傳(6)


1、靜態文件

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上傳</title>
</head>
<body>
    <form enctype="multipart/form-data" method="post" action="/v1/upload">
        文件:<input type="file" name="fileName"/></br></br>
        備注:<input type="text" name="remark"/>&nbsp;&nbsp;
        <input type="submit" value="上傳"/>
    </form>
</body>
</html>

2、return result

package cn.xiaobing.demo.pojo;

public class Result {
    private int code;
    private Object data;
    private String msg;
    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Result(int code, Object data, String msg) {
        super();
        this.code = code;
        this.data = data;
        this.msg = msg;
    }
    public Result() {
        super();
    }
    @Override
    public String toString() {
        return "Result [code=" + code + ", data=" + data + ", msg=" + msg + "]";
    }    
}

3、FileController

package cn.xiaobing.demo.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.xiaobing.demo.pojo.Result;

@Controller
@PropertySource(value = { "application.properties" })//指定配置文件
public class FileController {
    
    @Value("${web.upload.filepath}")//獲取配置文件中的配置參數
    private String filePath;
//  private static final String filePath = "C:/oneself/eclipse-workspace/springboot-v0/src/main/resources/static/images";
    
    @RequestMapping(value="/v1/upload")
    @ResponseBody
    public Object upload(@RequestParam("fileName") MultipartFile file,HttpServletRequest request) {
        String remark = request.getParameter("remark");//備注信息
        String filename = file.getOriginalFilename();//獲取文件名稱
        String suffixname = filename.substring(filename.lastIndexOf("."));//后綴
        filename = UUID.randomUUID() + suffixname;//文件上傳后重命名數據庫存儲
        File dest = new File(filePath,filename);
        Map<String, String> data = new HashMap<String, String>();
        data.put("filename", filename);
        data.put("備注 ", remark);
        try {
            //MultipartFile對象的transferTo方法用於文件的保存(效率和操作比原來用的FileOutputStream方便和高效)
            file.transferTo(dest);//拷貝文件到指定路徑儲存
            return new Result(0, data, "上傳成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(-1, data, "上傳失敗");
        }        
    }
}

4、啟動項目

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.1.RELEASE)

5、訪問upload.html上傳文件

 

 6、點擊上傳,上傳文件成功

 

 7、點擊上傳,上傳失敗

 8、設置上傳文件大小限制,編碼如下,在啟動類中添加@Bean方法

package cn.xiaobing.demo;
import javax.servlet.MultipartConfigElement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class XiaoBingApplication {
    public static void main(String[] args) {
        SpringApplication.run(XiaoBingApplication.class,args);
    }
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("10240KB");//設置上傳單個文件最大10M
        factory.setMaxRequestSize("102400KB");//設置上傳文件總數據最大100M    
        return factory.createMultipartConfig();
    }
}

9、maven打包執行

(1) pom.xml引入依賴

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

(2)打jar包-項目右鍵-Run As-Maven Install

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 45.874 s
[INFO] Finished at: 2020-06-29T23:44:45+08:00
[INFO] ------------------------------------------------------------------------

(3)啟動項目

 (4) Test

10、不足之處,后續優化。。。

 


免責聲明!

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



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