springboot中怎么实现文件上传
创始人
2024-12-24 16:21:57
0次

第一步编写上传的前段页面

 

     

     
         

                                 

                   

                                 

                   

                                 

                   

                                 

                   

                                 

                   

                                 

                   

           

                         

         

       
     

         

 

第二步写对应的js页面

/** * @Name:historyStorageCtrl,井史数据入库 * @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, //是否显示标题        showPreview: false, //是否显示预览区域        browseClass: "btn btn-primary", //按钮样式        previewFileIcon: "",      }).on('fileuploaderror', fileuploaderror).on("fileuploaded", function (event, data, previewId, index) {        // console.log(data);.on('fileselect', fileselect)        $scope.$apply(function () {          $scope.fileId = data.response.fileId; // 未执行          $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;    }        /**     *  文件上传错误     **/    function fileuploaderror(event, data, msg) {      $scope.fileInvalid = true;      $scope.$apply();      $('.modal-body .kv-upload-progress').css('display', 'none');      if (!(data.jqXHR.responseJSON)) { //文件类型验证错误        $('#fileError').html(msg);      } else { //上传错误        console.log(data);        var statusCode = data.jqXHR.responseJSON.message;        var errorMsg = HTTP_ERROR_MAP['' + statusCode];        $('#fileError').html(errorMsg);      }    }        /**     * add 打开添加模态框     */    $scope.openAddModal = function () {      $scope.document = {};      $scope.document.classificationId = 1;      $scope.document.starGrade = 5;      $timeout(importClearFunc);      // openModeldialog();    };             /**     * 表单验证     * @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("提示", "请填充表单", "info");        console.error("请填充表单");        return;      }       $scope.params = {        'introduction': $scope.document.introduction,//简介        'keyPackage': $scope.document.keyPackage,//可能查询的关键字        'starGrade': $scope.document.starGrade,//星级        '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("提示", "提交文件信息出错", "warning");        console.error("提交文件信息出错");      });    }      }])})(angular);

第三部编写后台上传文件和提交表单的代码

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 创建时间:2019年8月26日 上午11:54:22* @Description 类描述:*/@RestController@RequestMapping("/search")public class UploadFileController {@Autowiredprivate DocumentFileService dfservice;private String uploadPath="E://file";/** * 上传文件 * @param file * @return */@PostMapping("/upload")public Map uploadFile(MultipartFile file){Map map = new HashMap();try {      //文件的对象FileEntity fEntity = new FileEntity();String uuid = UUID.randomUUID().toString();//文件的idfEntity.setId(uuid.replaceAll("-", ""));//String.valueOf(Snowflake.getNextKey()));//文件的名字fEntity.setFileName(file.getOriginalFilename());//上传文件的时间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());//设置文件的类型fEntity.getDocType().setId(getDocTypeId(fEntity.getFileName()));//创建文件的对象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 submitFileInfo(@RequestBody DocumentFile df) {Map map = new HashMap();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;}}}

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...