springboot+element上传文件

package lesson.com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@SpringBootApplication
@RestController
public class Application {

	public static void main(String[] args) {

		SpringApplication.run(Application.class, args);
	}

	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*");
		corsConfiguration.addAllowedHeader("*");
		corsConfiguration.addAllowedMethod("*");
		corsConfiguration.setAllowCredentials(true);// 这两句不加不能跨域上传文件,
		corsConfiguration.setMaxAge(3600l);// 加上去就可以了
		return corsConfiguration;
	}

	/**
	 * 跨域过滤器
	 * 
	 * @return
	 */
	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig()); // 4
		return new CorsFilter(source);
	}
}

package lesson.com;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
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.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@CrossOrigin
public class FileUploadController {
	@RequestMapping("/upload")
	@ResponseBody
	public String handleFileUpload(@RequestParam("file") MultipartFile file) {
		System.out.println(System.getProperty("user.dir"));
		String path = System.getProperty("user.dir") + File.separator + "images";
		createDir(path);
		if (!file.isEmpty()) {
			try {
				BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(
						new File(path + File.separator + System.currentTimeMillis() + file.getOriginalFilename())));
				System.out.println(file.getName());
				out.write(file.getBytes());
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return "上传失败," + e.getMessage();
			} catch (IOException e) {
				e.printStackTrace();
				return "上传失败," + e.getMessage();
			}

			return "上传成功";

		} else {
			return "上传失败,因为文件是空的.";
		}
	}

	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {
			System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");
			return false;
		}
		if (!destDirName.endsWith(File.separator)) {
			destDirName = destDirName + File.separator;
		}
		// 创建目录
		if (dir.mkdirs()) {
			System.out.println("创建目录" + destDirName + "成功!");
			return true;
		} else {
			System.out.println("创建目录" + destDirName + "失败!");
			return false;
		}
	}
}

<template>
  <!--
  <div class="layout">
        <Layout>
            <Header>
                <Menu mode="horizontal" theme="dark" active-name="1">
                    <div class="layout-logo">
                        测试系统
                    </div>
                    <div class="layout-nav">
                        <MenuItem name="1">
                            <Icon type="ios-navigate"></Icon>
                            <router-link to="/RouteInfo">Go to Foo</router-link>
                        </MenuItem>
                    </div>
                </Menu>
            </Header>
            <Layout>
                <Sider hide-trigger :style="{background: '#fff'}">
                    <Menu active-name="1-2" theme="light" width="auto" :open-names="['1']" :style="{minHeight: '824px',}">
                        <Submenu name="1">
                            <template slot="title">
                                <Icon type="ios-navigate"></Icon>
                                项目信息
                            </template>
                            <MenuItem name="1-1"><router-link to="/RouteInfo">Go to Foo</router-link></MenuItem>
                            <MenuItem name="1-2"><router-link to="/projectone">项目一</router-link></MenuItem>
                            <MenuItem name="1-3"><router-link to="/projecttwo">项目二</router-link></MenuItem>
                        </Submenu>
                        <Submenu name="2">
                            <template slot="title">
                                <Icon type="ios-keypad"></Icon>
                                版本信息
                            </template>
                            <MenuItem name="2-1"><router-link to="/versionone">版本一</router-link></MenuItem>
                            <MenuItem name="2-2"><router-link to="/versiontwo">版本二</router-link></MenuItem>
                        </Submenu>
                    </Menu>
                </Sider>
                <Layout :style="{padding: '0 24px 24px'}">
                    <Content :style="{padding: '24px', minHeight: '800px', background: '#fff'}">
                        <router-view></router-view>
                    </Content>
                </Layout>
            </Layout>
        </Layout>
    </div>
  -->
  <div>
    <div id="myUpload">
      <el-button type="primary" size="mini" @click="uploadFile">导入</el-button>
      <!--上传-->
      <el-dialog title="上传" width="40%" :visible.sync="uploadTemplateDialog">
        <el-row>
          <el-col :span="22">
            <el-upload
              class="upload-demo"
              ref="upload"
              action
              :accept="acceptFileType"
              :limit="1"
              :on-exceed="handleExceed"
              :before-upload="beforeUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :auto-upload="false"
            >
              <el-button slot="trigger" size="small" type="primary">选取jpg格式文件</el-button>
              <div slot="tip" class="el-upload_tip">只能上传.jpg文件,且不超过1M</div>
            </el-upload>
          </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button @click="submitUpload" type="primary" size="mini" :loading="uploadLoading">确定上传</el-button>
          <el-button @click="uploadTemplateDialog=false" size="mini">取消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>


<script>
import HelloWorld from "./components/HelloWorld.vue";
import axios from "axios";
export default {
  components: {
    HelloWorld: HelloWorld
  },
  data() {
    return {
      message: "Hello Vue!",
      isCollapsed: false,
      fileList: [],
      uploadTemplateDialog: false,
      fileList: [],
      uploadLoading: false,
      acceptFileType: ".jpg",
      downLoadLoading: ""
    };
  },
  created: function() {},
  //钩子函数,页面加载完成后执行
  mounted() {},
  //函数方法
  methods: {
    uploadFile() {
      this.uploadLoading = false;
      var that = this;
      this.fileList = [];
      this.uploadTemplateDialog = true;
      setTimeout(function() {
        that.$refs.upload.clearFiles();
      }, 100);
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能选择1个文件!");
    },
    submitUpload() {
      this.uploadLoading = true;
      var that = this;
      setTimeout(function() {
        if (that.$refs.upload.$children[0].fileList.length == 1) {
          that.$refs.upload.submit();
        } else {
          that.uploadLoading = false;
          that.$message({
            type: "error",
            showClose: true,
            duration: 3000,
            message: "请选择文件!"
          });
        }
      }, 100);
    },
    handleRemove(file, fileList) {
      //console.log(file,fileList);
    },
    handlePreview(file) {
      //console.log(file);
    },
    beforeUpload(file) {
      var that = this;
      //文件类型
      var fileName = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (fileName != "jpg") {
        that.uploadTemplateDialog = false;
        that.$message({
          type: "error",
          showClose: true,
          duration: 3000,
          message: "文件类型不是.xls文件!"
        });
        return false;
      }
      //读取文件大小
      var fileSize = file.size;
      console.log(fileSize);
      if (fileSize > 1048576) {
        that.uploadTemplateDialog = false;
        that.$message({
          type: "error",
          showClose: true,
          duration: 3000,
          message: "文件大于1M!"
        });
        return false;
      }
      that.downloadLoading = that.$loading({
        lock: true,
        text: "数据导入中...",
        spinner: "el-icon-loading",
        background: "rgba(0,0,0,0.7)"
      });
      let fd = new FormData();
      fd.append("file", file);
      fd.append("_t1", new Date());
      axios({
        method: "post",
        url: "http://localhost:9007/upload/",
        data: fd,
        headers: {
          "Content-Type": "multipart/form-data;boundary=" + new Date().getTime()
        }
      })
        .then(rsp => {
          that.downloadLoading.close();
          that.uploadLoading = false;
          let resp = rsp.data;
          if (resp.resultCode == 200) {
            that.uploadTemplateDialog = false;
            that.$message.success(resp.resultMsg);
            //that.queryData();//更新数据
          } else {
            that.uploadTemplateDialog = false;
            that.$message({
              type: "error",
              showClose: true,
              duration: 60000,
              message: resp.resultMsg
            });
          }
        })
        .catch(error => {
          that.downloadLoading.close();
          that.uploadLoading = false;
          that.uploadTemplateDialog = false;
          that.$message({
            type: "error",
            showClose: true,
            duration: 60000,
            message: "请求失败! error:" + error
          });
        });
      return false;
    }
  }
};
</script>


<style scoped>
.layout {
  border: 1px solid #d7dde4;
  background: #f5f7f9;
  position: relative;
  border-radius: 4px;
  overflow: hidden;
}
.layout-logo {
  width: 100px;
  height: 30px;
  background: #5b6270;
  border-radius: 3px;
  float: left;
  position: relative;
  top: 15px;
  left: 20px;
  color: #ffffff;
  line-height: 30px;
  text-align: center;
}
.layout-nav {
  width: 420px;
  margin: 0 auto;
  margin-right: 20px;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值