springboot实现文件上传步骤解析

作者:求知若渴的蜗牛 时间:2023-01-31 22:15:42 

这篇文章主要介绍了springboot实现文件上传步骤解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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


<div>
 <button type="button" class="btn btn-primary" ng-click="openAddModal()" data-toggle="modal"
   data-target="#documentOprModal" style="margin-left: 10px;float:left">
   单个文件上传
 </button>
</div>

<!-- 点击单个文件上传弹出的模态框 -->
<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" style="width: 600px;">
   <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>
       <h4 class="modal-title" id="myModalLabel"> 文档入库</h4>
     </div>
     <div class="modal-body">
       <!--开发-->
       <form name="docForm" id="docForm">
         <div class="form-group">
           <label for="jhText">井号:</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>
         <!-- 可能的查询关键字 -->
         <div class="form-group">
           <label for="keyPackageTextArea">可能的查询关键字:</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" style="margin: 0px 20px;">
         <i class="fa fa-ban"></i>取消
       </button>
     </div>
   </div>
 </div>
</div>

第二步写对应的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: "<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; // 未执行
         $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 {

@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 {
     //文件的对象
FileEntity fEntity = new FileEntity();
String uuid = UUID.randomUUID().toString();
//文件的id
fEntity.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<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;
}
}
}

来源:https://wo.jb51.net/admin/index.asp

标签:spring,boot,文件,上传,步骤
0
投稿

猜你喜欢

  • C#开发Winform控件之打开文件对话框OpenFileDialog类

    2023-04-19 10:53:16
  • Android中LayoutInflater.inflater()的正确打开方式

    2022-04-12 16:25:57
  • java微信公众号开发第一步 公众号接入和access_token管理

    2022-04-21 23:06:41
  • Java聊天室之实现接收和发送Socket

    2021-06-24 23:30:39
  • Android编程自定义菜单实现方法详解

    2022-08-25 18:16:08
  • java实现单机版五子棋

    2022-12-20 20:15:07
  • Android DownloadMananger管理器实现下载图片功能

    2022-05-06 03:20:24
  • Java中值类型和引用类型详解

    2023-11-29 00:44:51
  • 点九图片的显示内容区域应作何理解

    2022-12-27 12:24:30
  • Java实现多用户注册登录的幸运抽奖

    2023-07-30 11:57:44
  • java新特性之for循环最全的用法总结

    2022-07-08 22:14:51
  • Java内存模型final的内存语义

    2023-06-05 08:02:25
  • java list集合排序按某一属性排序操作

    2021-06-24 03:33:25
  • JAVA面试题 从源码角度分析StringBuffer和StringBuilder的区别

    2023-07-24 07:29:07
  • Spring Security 中如何让上级拥有下级的所有权限(案例分析)

    2022-01-28 16:55:26
  • Android UI设计系列之ImageView实现ProgressBar旋转效果(1)

    2021-06-07 11:08:21
  • Android实现简单的照相功能

    2023-07-01 08:46:16
  • Spring Security验证流程剖析及自定义验证方法

    2023-10-01 22:05:58
  • Java实现的质因数分解操作示例【基于递归算法】

    2023-08-19 03:22:12
  • C#递归实现回文判断算法

    2022-06-14 13:45:16
  • asp之家 软件编程 m.aspxhome.com