溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot如何實(shí)現(xiàn)文件上傳步驟解析

發(fā)布時(shí)間:2021-05-24 11:34:25 來源:億速云 閱讀:166 作者:小新 欄目:編程語言

小編給大家分享一下springboot如何實(shí)現(xiàn)文件上傳步驟解析,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

第一步編寫上傳的前段頁面

<div>
  <button type="button" class="btn btn-primary" ng-click="openAddModal()" data-toggle="modal"
    data-target="#documentOprModal" >
    單個(gè)文件上傳
  </button>
</div>
 
<!-- 點(diǎn)擊單個(gè)文件上傳彈出的模態(tài)框 -->
<div class="modal fade" id="documentOprModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog modal-lg" role="document" >
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
            aria-hidden="true">&times;</span></button>
        <h5 class="modal-title" id="myModalLabel"> 文檔入庫</h5>
      </div>
      <div class="modal-body">
        <!--開發(fā)-->
        <form name="docForm" id="docForm">
          <div class="form-group">
            <label for="jhText">井號(hào):</label>
            <input type="text" class="form-control" id="jhText" ng-model="document.jh">
          </div>
          <!-- 作者 -->
          <div class="form-group">
            <label for="authorText">作者:</label>
            <input type="text" class="form-control" id="authorText" ng-model="document.author">
          </div>
          <!-- 單位 -->
          <div class="form-group">
            <label for="unitText">單位:</label>
            <input type="text" class="form-control" id="unitText" ng-model="document.unit">
          </div>
          <!-- 日期 -->
          <div class="form-group">
            <label for="writeDate">寫作日期:</label>
            <input type="date" class="form-control" id="writeDate" ng-model="document.writeDate">
          </div>
          <!-- 簡介 -->
          <div class="form-group">
            <label for="introductionTextArea">簡介:</label>
            <textarea class="form-control" id="introductionTextArea" ng-model="document.introduction"
              rows="5" cols="60"></textarea>
          </div>
          <!-- 可能的查詢關(guān)鍵字 -->
          <div class="form-group">
            <label for="keyPackageTextArea">可能的查詢關(guān)鍵字:</label>
            <textarea class="form-control" id="keyPackageTextArea" ng-model="document.keyPackage" rows="5"
              cols="60"></textarea>
          </div>
          <!-- 文件 -->
          <div class="form-group">
            <div id="inputContent">
              <input id="importFile" type="file" name="file" class="file-loading">
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" ng-click="submitFileInfo()">
          <i class="fa fa-check"></i>保存
        </button>
        <button type="button" class="btn btn-default" data-dismiss="modal" >
          <i class="fa fa-ban"></i>取消
        </button>
      </div>
    </div>
  </div>
</div>

第二步寫對(duì)應(yīng)的js頁面

/**
 * @Name:historyStorageCtrl,井史數(shù)據(jù)入庫
 * @Date:2019-06-19
 * @Author:huofenwei
 */
(function (angular) {
  'use strict';
  angular.module('Lujing').controller('historyStorageCtrl', ['$scope', '$http', 'ToastService', '$compile', '$timeout', 'HttpService','$filter',
  function ($scope, $http, ToastService, $compile, $timeout, HttpService,$filter) {
    $scope.fileInvalid = false;

    var $fileInput = initFileInput("importFile", '/server/search/upload');

    /**
     *初始化文件上傳
     */
    function initFileInput(ctrlName, uploadUrl) {
      var control = $('#' + ctrlName);
      control.fileinput({
        language: 'zh',
        uploadUrl: uploadUrl, //上傳的地址
        allowedFileExtensions: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'mp4', 'avi','wmv','asf','asx','rm','rmvb','3gp','mov','m4v','dat','mkv','flv','vob'],
        showUpload: true, //是否顯示上傳按鈕
        showCaption: true, //是否顯示標(biāo)題
        showPreview: false, //是否顯示預(yù)覽區(qū)域
        browseClass: "btn btn-primary", //按鈕樣式
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
      }).on('fileuploaderror', fileuploaderror).on("fileuploaded", function (event, data, previewId, index) {
        // console.log(data);.on('fileselect', fileselect)
        $scope.$apply(function () {
          $scope.fileId = data.response.fileId; // 未執(zhí)行
          $scope.document.fileName = data.files[0].name;
        });

      }).on("filecleared", function (event, data, msg) {
        $scope.$apply(function () {
          $scope.fileInvalid = false;
        });
      });
      return control;
    }

    /**
     * 清空輸入框
     */
    function importClearFunc() {
      if ($fileInput)
        $fileInput.fileinput('clear');
      $scope.fileInvalid = false;
    }

    

    /**
     *  文件上傳錯(cuò)誤
     **/
    function fileuploaderror(event, data, msg) {
      $scope.fileInvalid = true;
      $scope.$apply();
      $('.modal-body .kv-upload-progress').css('display', 'none');
      if (!(data.jqXHR.responseJSON)) { //文件類型驗(yàn)證錯(cuò)誤
        $('#fileError').html(msg);
      } else { //上傳錯(cuò)誤
        console.log(data);
        var statusCode = data.jqXHR.responseJSON.message;
        var errorMsg = HTTP_ERROR_MAP['' + statusCode];
        $('#fileError').html(errorMsg);
      }
    }

    
    /**
     * add 打開添加模態(tài)框
     */
    $scope.openAddModal = function () {
      $scope.document = {};
      $scope.document.classificationId = 1;
      $scope.document.starGrade = 5;
      $timeout(importClearFunc);
      // openModeldialog();
    };
         

    /**
     * 表單驗(yàn)證
     * @returns {boolean}
     */
    function formVlidate() {
      if (!$scope.document.introduction) {
        return false;
      }
      if (!$scope.document.keyPackage) {
        return false;
      }
      return true;
    }

    /**
     * 提交表單信息
     */
    $scope.submitFileInfo = function () {
      if (!$scope.fileId) {
        // ToastService.alert("提示", "先上傳文件,再提交表單", "info");
        console.error("先上傳文件,再提交表單");
        return;
      }
      if (!formVlidate()) {
        // ToastService.alert("提示", "請(qǐng)?zhí)畛浔韱?quot;, "info");
        console.error("請(qǐng)?zhí)畛浔韱?quot;);
        return;
      } 
      $scope.params = {
        'introduction': $scope.document.introduction,//簡介
        'keyPackage': $scope.document.keyPackage,//可能查詢的關(guān)鍵字
        'starGrade': $scope.document.starGrade,//星級(jí)
        'classificationId': $scope.document.classificationId,//文件的id
        'filePath': $scope.fileId,//文件的路徑
        'docName': $scope.document.fileName,//文件的名字
        'author':$scope.document.author,
        'unit':$scope.document.unit,
        'writeDate':$scope.document.writeDate?$scope.document.writeDate.format("yyyy-MM-dd hh:mm:ss"):$scope.document.writeDate,
        'jh': $scope.document.jh,
        'id': $scope.document.id
      };
      HttpService.post("/server/search/submit", $scope.params).then(function (data) {
        $('#documentOprModal').modal('hide');
        // $("#contTable").bootstrapTable('refresh');
        console.error("提交文件信息成功");
      }, function (response) {
        // ToastService.alert("提示", "提交文件信息出錯(cuò)", "warning");
        console.error("提交文件信息出錯(cuò)");
      });
    }


    
  }
])
})(angular);

第三部編寫后臺(tái)上傳文件和提交表單的代碼

package com.shiwen.yitihui.server.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.shiwen.yitihui.common.Snowflake;
import com.shiwen.yitihui.domain.DocClassification;
import com.shiwen.yitihui.domain.DocType;
import com.shiwen.yitihui.domain.DocumentFile;
import com.shiwen.yitihui.domain.FileEntity;
import com.shiwen.yitihui.server.service.DocumentFileService;

/**
* @author wangjie:
* @version 創(chuàng)建時(shí)間:2019年8月26日 上午11:54:22
* @Description 類描述:
*/
@RestController
@RequestMapping("/search")
public class UploadFileController {
	
	@Autowired
	private DocumentFileService dfservice;
	
	private String uploadPath="E://file";
	
	/**
	 * 上傳文件
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	public Map<String, Object> uploadFile(MultipartFile file){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
      //文件的對(duì)象
			FileEntity fEntity = new FileEntity();
			String uuid = UUID.randomUUID().toString();
			//文件的id
			fEntity.setId(uuid.replaceAll("-", ""));//String.valueOf(Snowflake.getNextKey()));
			//文件的名字
			fEntity.setFileName(file.getOriginalFilename());
			//上傳文件的時(shí)間
			fEntity.setUploadTime(new Date());
			//上傳者
			fEntity.setUploadBy("admin");
			//文件的后綴
			String suffix = fEntity.getFileName().substring(fEntity.getFileName().indexOf("."));
			//文件存放的完整路徑
			fEntity.setFinePathName(uploadPath + File.separator + fEntity.getId() + suffix);
			//文件的類型
			fEntity.setDocType(new DocType());
			//設(shè)置文件的類型
			fEntity.getDocType().setId(getDocTypeId(fEntity.getFileName()));
			//創(chuàng)建文件的對(duì)象
			File newFile = new File(fEntity.getFinePathName());
			//上傳文件
			file.transferTo(newFile);
			map.put("result", "success");
			map.put("fileId", fEntity.getId());
		}catch(Exception e) {
//			e.printStackTrace();
			map.put("result", "fail");
		}
		return map;
		
	}
	
	/**
	 * 提交表單
	 * @param df
	 * @return
	 */
	@PostMapping("/submit")
	public Map<String, Object> submitFileInfo(@RequestBody DocumentFile df) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			if (df.getId() == null || df.getId().isEmpty() || df.getId() == "") {
				df.setId(String.valueOf(Snowflake.getNextKey()));
			}
			String suffix = df.getDocName().substring(df.getDocName().indexOf("."));
			df.setFilePath(uploadPath + File.separator + df.getFilePath() + suffix);
			df.setUploadBy("admin");// 用戶名稱 df.setUploadTime(new java.util.Date());
			df.setUploadTime(new Date());
			df.setDownloadNumber(0L);
			df.setHeat(0L);
			df.setRelated(20);
			df.setDocType(new DocType());
			df.getDocType().setId(getDocTypeId(suffix));
			df.setClassification(new DocClassification());
			df.getClassification().setId(df.getClassificationId());
			dfservice.save(df);
			map.put("result", "success");
		} catch (Exception e) {
			//e.printStackTrace();
		  map.put("result", "fail");
		}
		return map;
	}
	
	
	
	private Integer getDocTypeId(String fileName) {
		if (fileName.contains(".doc")) {
			return 1;
		} else if (fileName.contains(".xls")) {
			return 2;
		} else if (fileName.contains(".pdf")) {
			return 3;
		} else if (fileName.contains(".ppt")) {
			return 4;
		}else {
			return 5;
		}
	}
}

看完了這篇文章,相信你對(duì)“springboot如何實(shí)現(xiàn)文件上傳步驟解析”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI