SpringBootはシンプルなアップロード機能を実現

#はじめに
#春のブートサーバボタン
1、pom.xml文件多重依赖
  <dependency> 
            < groupId > org.springframework.boot </ groupId> 
            <artifactId> spring-boot-starter-thymeleaf </ artifactId> 
   </ dependency> 
2、yml文件添加配置参数
サーバー:
  ポート:8080
  サーブレット:
    コンテキストパス:/デモ
スプリング:
  サーブレット:
    マルチパート:
      有効:真の
      場所:D:\
      ファイルサイズしきい値:5MB
      最大ファイルサイズ:20MB 
  mvc:
    ビュー:
      プレフィックス:クラスパス:/ templates /
      サフィックス:.html 
    static-path-pattern:/ static / **

3.テンプレートディレクトリにindex.htmlを追加し
    ます
    。4。MVC
はページジャンプを実現します。メソッド1. @ Controller 
    public class IndexController { 
        @GetMapping( "")
        public String index(){ 
            return "index"; 
        } 
    }
    メソッド2. 
   @ RestController 
   public class IndexController { 
       @GetMapping( "")
       public ModelAndView index(){ 
           ModelAndView modelAndView = new ModelAndView(); 
           modelAndView.setViewName( "index"); 
           return modelAndView; 
       } 
   } 
   RestControllerはController + RequestBodyと同等であるため、 RestControllerビューパーサー
  5を構成する必要があり、ファイルのアップロードを実現するためのコード

具体的なコードは次のとおりです。

1.アップロード機能

@RestController 
@RequestMapping( "upload")
@ Slf4j 
public class UploadController { 
    @Value( "$ {spring.servlet.multipart.location}")
    private String fileTempPath; 

    @PostMapping(value = "/ local"、consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Dict local(@RequestParam( "file")MultipartFile file){ 
        if(file.isEmpty()){ 
            return Dict.create()。set( " code "、400).set(" message "、"文件内容是空 "); 
        } 
        String fileName = file.getOriginalFilename(); 
        String rawFileName = StrUtil.subBefore(fileName、 "。"、true);
        String fileType = StrUtil.subAfter(fileName、 "。"、
        String localFilePath = StrUtil.appendIfMissing(fileTempPath、 "/")+ rawFileName + "-" + DateUtil.current(false)+ "。" + fileType; 
        try { 
            file.transferTo(new File(localFilePath)); 
        } catch(IOException e){ 
            log.error( "[ローカルへのファイルのアップロード]に失敗しました、絶対パス:{}"、localFilePath); 
            return Dict.create()。set( "code"、500).set( "message"、 "Fileアップロードに失敗しました "); 
        } 

        log.info(" [ローカルへのファイルのアップロード]絶対パス:{} "、localFilePath); 
        return Dict.create()。set(" code "、200).set(" message "、"正常にアップロードされました ")。set(" data "、Dict.create()。set(" fileName "、fileName).set(" filePath "、localFilePath));
    } 

}

2、index.html

<!doctype html> 
<html lang = "en"> 
<head> 
   <meta charset = "UTF-8"> 
   <meta name = "viewport" 
         content = "width = device-width、user-scalable = no、initial- scale = 1.0、maximum-scale = 1.0、minimum-scale = 1.0 "> 
   <meta http-equiv =" X-UA-Compatible "content =" ie = edge "> 
   <title> spring-boot-demo-upload </タイトル> 
   <!-import Vue.js-> 
   <script src = "https://cdn.bootcss.com/vue/2.5.17/vue.min.js"> </ script> 
   <!-importスタイルシート-> 
   <link href = "https://cdn.bootcss.com/iview/3.1.4/styles/iview.css" rel = "stylesheet"> 
   <!-import iView->
   <script src = "https://cdn.bootcss.com/iview/3.1.4/iview.min.js"> </ script> 
</ head> 
<body>
<div id = "app"> 
   <Row:gutter = "16" style = "background:#eee; padding:10%"> 
      <i-col span = "12"> 
         <Card style = "height:300px"> 
            <p slot = "title"> 
               <Icon type = "ios-cloud-upload"> </ Icon>本
               房MOSFET 
            </ p> 
            <div style = "text-align:center;"> 
               <アップロード
                     :before-upload = "handleLocalUpload" 
                     action = "/ demo / upload / local" 
                     ref = "localUploadRef" 
                     :on-success = "handleLocalSuccess"
                     :on-error = "handleLocalError" 
               >
                  <i-buttonicon = "ios-cloud-upload-outline">選択择文件</ i-button> 
               </アップロード> 
               <i-button 
                     type = "primary" 
                     @ click = "localUpload" 
                     :loading = "local.loadingStatus " 
                     :disabled ="!local.file "> 
                  { 
  
  {local.loadingStatus?'本地文件上アップロード中': '本卓ا'}} 
               </ i-button> 
            </ div> 
            <div> 
               <div v-if = "local.log.status!= 0">事态:{ 
  
  {local.log .message}} </ div> 
               <div v-if = "local.log。
  
  
               <div v-if = "local.log.status === 200">ファイルパス:{ 
  
  {local.log.filePath}} </ div> 
            </ div> 
         </ Card> 
      </ i-col> 
   </行> 
</ div> 
<script> 
   new Vue({ 
      el: '#app'、
      data:{ 
         local:{ 
            //ファイルを選択した後、beforeUploadによって返されたファイルをここに保存します。
            ファイル:null、//
            アップロードステータスをマークします
            LoadingStatus:false、
            log:{ 
               status:0、
               message: ""、
               fileName: ""、
               filePath: ""
            } 
         }、
         ユン:{
            //ファイルを選択した後、beforeUploadによって返されたファイルをここに保存します。file 
            :nullは後で使用され
            ます
            。//アップロードステータスをマークしますloadingStatus:false、
            log:{ 
               status:0、
               message: ""、
               fileName: ""、
               filePath: "" 
            } 
         } 
      }、
      methods:{ 
         // beforeUploadは、falseまたはPromiseを返すと、自動アップロードを停止します。ここでは、選択したファイルファイルをデータに保存し、falseを返します
         。handleLocalUpload(file){ 
            this.local。file= file; 
            return false; 
         }、
         //これは手動アップロードです。Uploadインスタンスは$ refsを介して取得され、プライベートメソッド.post()が呼び出されてデータに保存されたファイルがアップロードされます。
         // iViewのUploadコンポーネントが.post()メソッドを呼び出すと、アップロードが続行されます。
         localUpload(){ 
            this.local.loadingStatus = true; //アップロードステータスをマークします
            this。$ refs.localUploadRef.post(this.local.file); 
         }、
         //アップロードが成功したら、データ内のファイルをクリアしますアップロードステータスを変更します
         handleLocalSuccess(response){ 
            this.local.file = null; 
            this.local.loadingStatus = false; 
            if(response.code === 200){ 
               this。$ Message.success(response.message); 
               this .local.log .status = response.code; 
               this.local.log.message = response.message; 
               this.local.log.fileName = response.data.fileName;
               this.local.log.filePath = response.data.filePath; 
               this。$ refs.localUploadRef.clearFiles(); 
            } else { 
               this。$ Message.error(response.message); 
               this.local.log.status = response。 code; 
               this.local.log.message = response.message; 
            } 
         }、
         //アップロードが失敗した後、データ内のファイルをクリアし、アップロードステータスを変更します
         handleLocalError(){ 
            this.local.file = null; 
            this.local。 LoadingStatus = false; 
            this。$ Message.error( 'Upload failed'); 
         }、
         // beforeUploadはfalseまたはPromiseを返すと自動アップロードを停止します。ここでは、選択したファイルファイルをデータに保存してfalseを返します。
         handleYunUpload(file){ 
            this.yun.file = file; 
            return false; 
         }、
         //これは手動アップロードです。Uploadインスタンスは$ refsを介して取得され、プライベートメソッド.post()が呼び出されて保存されたファイルがアップロードされます。データ内。
         // iViewのUploadコンポーネントが.post()メソッドを呼び出すと、アップロードが続行されます。
         yunUpload(){ 
            this.yun.loadingStatus = true; //アップロードステータスをマークします
            this。$ refs.yunUploadRef.post(this.yun.file); 
         }、
         //アップロードが成功したら、データ内のファイルをクリアしますアップロードステータスを変更します
         handleYunSuccess(response){ 
            this.yun.file = null; 
            this.yun.loadingStatus = false; 
            if(response.code === 200){ 
               this。$ Message.success(response.message);
               this.yun.log.status = response.code; 
               this.yun.log.message = response.message; 
               this.yun.log.fileName = response.data.fileName; 
               this.yun.log.filePath = response.data.filePath; 
               this。$ refs.yunUploadRef.clearFiles(); 
            } else { 
               this。$ Message.error(response.message); 
               this.yun.log.status = response.code; 
               this.yun.log.message = response.message; 
            } 
         }、
         //上衣失败后、清空データ里的ファイル、完了ファイルアップロード上事項态
         handleYunError(){ 
            this.yun.file = null; 
            this.yun.loadingStatus = false;
            this。$ Message.error( '上MOSFET失败'); 
         } 
      } 
   })
</ script> 
</ body> 
</ html>

おすすめ

転載: blog.csdn.net/A___B___C/article/details/107971659