Angular14 利用Angular2实现文件上传的前端、利用springBoot实现文件上传的后台、跨域问题
一、angular2实现文件上传前端
Angular2使用ng2-file-upload上传文件,Angular2中有两个比较好用的上传文件的第三方库,一个是ng2-file-upload
,一个是ng2-uploader
。ng2-uploader
是一个轻便的上传文件的支持库,功能较弱,而ng2-file-upload
是一个功能比较全面的上传文件的支持库。这里主要介绍一下ng2-file-upload
的使用。
1 下载相关模块
进入到项目根目录执行 npm install ng2-file-upload --save
坑01:有时候利用npm下载不成功
2 在主模块中导入上传模块
技巧01:一般都是在共享模块中导入再导出,然后在需要的模块中导入共享模块就可以啦
3 编写上传文件组件
import { Component, OnInit } from '@angular/core';
import {FileUploader} from 'ng2-file-upload'; @Component({
selector: 'app-test-upload-file',
templateUrl: './test-upload-file.component.html',
styleUrls: ['./test-upload-file.component.css']
})
export class TestUploadFileComponent implements OnInit {
private uploader: FileUploader = new FileUploader({
url: '/devProject/uploadClient',
method: 'POST',
itemAlias: 'file'
}); constructor() { } ngOnInit() {
} /**
* 上传文件内容变化时执行的方法
* @param event
*/
selectedFileOnChanged(event: any) {
// 这里是文件选择完成后的操作处理
// alert('上传文件改变啦');
console.log(event.target.value);
console.log(event);
} /**
* 上传文件方法
*/
uploadFile() {
alert('执行上传文件');
// 上传
this.uploader.queue[].onSuccess = function (response, status, headers) {
// 上传文件成功
if (status == ) {
// 上传文件后获取服务器返回的数据
const tempRes = response;
alert(response);
} else {
// 上传文件后获取服务器返回的数据错误
alert('上传失败');
}
};
// onSuccessItem(item: FileItem, response: string, status: number, headers: ParsedResponseHeaders): any;
this.uploader.queue[].upload(); // 开始上传
// this.uploader.queue[0].onSuccess()
alert('上传之后');
}
}
4 HTML文件
<p>
test-upload-file works!
</p>
<hr style="border: 1px solid blue;" /> <input type="file" ng2FileSelect [uploader]="uploader" (change)="selectedFileOnChanged($event)" />
<button (click)="uploadFile()">点击上传</button>
详情请参见:点击前往
二、SpringBoot实现后台功能
/**
* 上传客户EXCEL表格
* @param file
* @return 上传成功信息
* @throws IOException
*/
@PostMapping("/uploadClient")
public String testUpload(@RequestParam("file") MultipartFile file) throws IOException {
// System.out.println("后台文件上传函数");
// System.out.println("获取到的文件名称为:" + file);
String filePath = file.getOriginalFilename(); // 获取文件的名称
filePath = "asset/" + filePath; // 这是文件的保存路径,如果不设置就会保存到项目的根目录 BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath)); outputStream.write(file.getBytes());
outputStream.flush();
outputStream.close();
return "客户资料上传成功";
}
坑01:文件上传时会出现跨域问题,最简单的方法就是在后台配置一个跨域配置,就是编写一个类,然后在需要跨域的类中继承这个类就可以啦
参考博文:点击前往
package cn.xiangxu.cq8x.configure; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /**
* @author 王杨帅
* @create 2018-03-22 15:51
* @desc 跨域配置
**/
@Configuration
public class CorsConfigure extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
.allowCredentials(true).maxAge(3600);
}
}
package cn.xiangxu.cq8x.controller; import cn.xiangxu.cq8x.configure.CorsConfigure;
import cn.xiangxu.cq8x.dao.ClientDao;
import cn.xiangxu.cq8x.model.dataModel.ClientInfoModel;
import cn.xiangxu.cq8x.model.viewModel.ResultViewModel;
import cn.xiangxu.cq8x.service.ClientService;
import cn.xiangxu.cq8x.util.ResultViewUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException; /**
* @author 王杨帅
* @create 2018-03-06 20:36
* @desc 客户信息控制层接口
**/
@RestController
@RequestMapping(value = "/client")
@CrossOrigin
public class ClientController extends CorsConfigure { @Resource(name = "clientService")
private ClientService clientService; /**
* 查询所有的客户信息
* @return
*/
@GetMapping(value = "/findAll")
public ResultViewModel findAll(
@RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
@RequestParam(value = "size", required = false, defaultValue = "3") Integer size
) {
Pageable pageable = PageRequest.of(page, size);
System.out.println(pageable);
return ResultViewUtil.success(clientService.findAll(pageable));
} /**
* 根据姓名查询客户信息
* @param name 从路径中获取参数
* @return
*/
@GetMapping(value = "/findByName02/{name}")
public ResultViewModel findByName02(
@PathVariable("name") String name
) {
System.out.println("前端传过来的目标客户姓名为:" + name);
return ResultViewUtil.success(clientService.findByName(name));
} /**
* 根据姓名查询客户信息
* @param name 从query中获取参数
* @return
*/
@GetMapping(value = "/findByName")
public ResultViewModel findByName(
@RequestParam("name") String name
) {
System.out.println("从前端获取到的参数为:" + name);
return ResultViewUtil.success(clientService.findByName(name));
} /**
* 根据姓名进行模糊查询
* @param name
* @return
*/
@GetMapping(value = "/findByNameLike/{name}")
public ResultViewModel findByNameLike(
@PathVariable("name") String name
) {
System.out.println("前端传过来的模糊查询信息为 :" + name);
return ResultViewUtil.success(clientService.findByNameLike(name));
} /**
* 根据idcard查询客户信息
* @param idcard 从路径中获取参数
* @return
*/
@GetMapping(value = "/findByIdcard02/{idcard}")
public ResultViewModel findByIdcard02(
@PathVariable("idcard") String idcard
) {
System.out.println("前端传过来的客户证件号码为:" + idcard);
return ResultViewUtil.success(clientService.findByIdcard(idcard));
} /**
* 根据idcard查询客户信息
* @param idcard 从query中获取参数
* @return
*/
@GetMapping(value = "/findByIdcard")
public ResultViewModel findByIdcard(
@RequestParam("idcard") String idcard
) {
System.out.println("从前端获取到的参数为:" + idcard);
return ResultViewUtil.success(this.clientService.findByIdcard(idcard));
} /**
* 新增客户
* @param clientInfoModel
* @return
*/
@PostMapping(value = "/create")
public ResultViewModel create(
@RequestBody ClientInfoModel clientInfoModel
) {
return ResultViewUtil.success(this.clientService.createNewClient(clientInfoModel));
} @PutMapping(value = "/update")
public ResultViewModel update(
@RequestBody ClientInfoModel clientInfoModel
) {
System.out.println(clientInfoModel);
return ResultViewUtil.success(this.clientService.updateClient(clientInfoModel));
} @CrossOrigin
@PostMapping(value = "/upload")
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
// System.out.println("后台文件上传函数");
System.out.println("获取到的文件名称为:" + file);
String filePath = file.getOriginalFilename(); // 获取文件的名称
filePath = "G:/" + filePath; // 这是文件的保存路径,如果不设置就会保存到项目的根目录 BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath)); outputStream.write(file.getBytes());
outputStream.flush();
outputStream.close(); return "客户资料上传成功";
} @GetMapping(value = "/test")
public ResultViewModel test(
@RequestParam("id") Integer id
) {
return ResultViewUtil.success("这是一个测试接口");
} @PutMapping(value = "/test02")
public ResultViewModel test02(
@RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
@RequestParam(value = "size", required = false, defaultValue = "3") Integer size
) {
System.out.println("获取到的参数page为:" + page);
System.out.println("获取到的参数size为:" + size);
return ResultViewUtil.success("PUT方法的参数问题");
} }
·下面是我的公众号二维码,欢迎关注·
尋渝記
微信号:xyj_fury
Angular14 利用Angular2实现文件上传的前端、利用springBoot实现文件上传的后台、跨域问题的更多相关文章
- Angular2发送HTTP请求SpringBoot后台跨域问题解决
Angular通过http发送post请求至SpringBoot的Controller,由于同源策略的保护,遇到跨域问题: • 源(origin)就是协议(http).域名(localhost)和端口 ...
- 利用 jrebel 热部署\远程调试\远程热部署 springboot项目 服务器上的代码
首先要在eclipse 中启用 启用以后在 resource 中生成了 rebel-remote.xml 然后build,把生成的jar包放到服务器上. 然后用下面的命令启动 java -agentp ...
- Asp.Net Core 3.0 学习3、Web Api 文件上传 Ajax请求以及跨域问题
1.创建Api项目 我用的是VS2019 Core3.1 .打开Vs2019 创建Asp.Net Core Web应用程序命名CoreWebApi 创建选择API 在Controller文件夹下面添加 ...
- 七牛---以一个七牛上传的实例小结下AJAX跨域【转】
http://blog.csdn.net/netdxy/article/details/50699842 使用七牛过程中,很多用户或多或少遇到跨域的问题,这篇文章主要介绍下跨域的概念来看什么情况下会出 ...
- NetCore 上传,断点续传,可支持流上传
之前公司要做一个断点续传的业务,找了许多都没有找到合适的,都是残次不全的,终于让我遇到一个基于百度的 webuploader 的断点续传.原作者: 断点续传(上传)( https://www.some ...
- 利用Nginx轻松实现Ajax的跨域请求(前后端分离开发调试必备神技)
利用Nginx轻松实现浏览器中Ajax的跨域请求(前后端分离开发调试必备神技) 前言 为什么会出现跨域? 造成跨域问题的原因是因为浏览器受到同源策略的限制,也就是说js只能访问和操作自己域下的资源,不 ...
- gulp 搭建个人工作流:文件注入、热启动、跨域
个人比价推崇前后端分离的开发方式,大家伙各司其职,只需通过 API 进行交流,不仅避免了沟通上的成本,更提升了开发效率.而在前端开发工作中,许多需求和问题是相似的,所以我们的开发模式往往是雷同的,是否 ...
- 跨域策略文件crossdomain.xml文件
使用crossdomain.xml让Flash可以跨域传输数据 一.crossdomain.xml文件的作用 跨域,顾名思义就是需要的资源不在自己的域服务器上,需要访问其他域服务器.跨域策略文件 ...
- 谷歌通过ajax获取本地JSON文件,为什么会显示跨域?转载的
在本地写了一段JSON代码,然后用ajax读取后,在浏览器打开,发现谷歌提示涉及到跨域问题, 但是跨域是由于协议,域名,端口中有一个不同,才会跨域,我在本地访问自己的文件,怎么和跨域扯上关系了?? 谷 ...
- 谷歌通过ajax获取本地JSON文件,为什么会提示跨域?
在本地写了一段JSON代码,然后用ajax读取后,在浏览器打开,发现谷歌提示涉及到跨域问题, 但是跨域是由于协议,域名,端口中有一个不同,才会跨域,我在本地访问自己的文件,怎么和跨域扯上关系了?? 下 ...
随机推荐
- 重新认识Java中的程序入口即主函数各组成部分
主函数各组成部分深入理解 public static void main(String[] agrs) 主函数:是一个特殊的函数,作为程序的入口,可以被JVM调用 主函数的定义: public:代表着 ...
- 对类型化数组(Typed Array)与ArrayBuffer的理解 转囧囧
类型化数组(Typed Array)也是HTML5中新引入的API.用一句话解释类型化数组就是:它是JS操作二进制数据的接口. 众所周知,直接操作二进制数据可以使程序更为高效, 尽管JS对常规数组做了 ...
- slam kf
一.KF 1.从概率来理解概率估计因为希望整个运动估计较长时间内最优,所以反而会用最新的知识去更新之前的状态,就比如在做完当前帧的位姿估计的时候,修改局部地图的路标点.如果站在之前的状态上来考虑,用的 ...
- TMS Scripter importtool的使用
uses ap_DateUtils; showmessage(dayof(now)); //注册delphi对象或变量 : IDEScripter1 IDEScripter1.AddConstan ...
- Hibernate和Struts分页查询
分页查询数据库方法 /** * 分页查询方法 * @param sql,pageNO,maxResult * @return List */ public List<Object> que ...
- requests获取响应时间(elapsed)与超时(timeout)
前言 requests发请求时,接口的响应时间,也是我们需要关注的一个点,如果响应时间太长,也是不合理的.如果服务端没及时响应,也不能一直等着,可以设置一个timeout超时的时间 关于request ...
- linux 下载rpm包到本地,createrepo:创建本地YUM源
如何下载rpm包到本地 设置yum安装时,保留rpm包. 1.编辑 /etc/yum.conf 将keepcache的值设置为1; 这样就可以将yum安装时的rpm包保存在 /var/cache/yu ...
- Mysql: 强制走索引:mysql between 日期索引 索引问题-日期索引使用
Mysql: mysql between 日期索引 索引问题-日期索引使用 表结构: dep_date dep arr 联合索引: ind_coll_date_route (dep_date ,de ...
- 初识JQuery(1)-选择器
初识jquery 在学习jquery之前,就有看过一些相关的视频,才知道它是可以写很少的代码就可以完成很多事的.记得第一写轮播图的时候,首先就百度了篇轮播图的实现,当时还不知道自己百度的其实不是原生的 ...
- web网页打印的方法
WebBrowser.ExecWB的完整说明 个人感觉的:致命缺点-----------------仅仅支持ie浏览器 document.all.WebBrowser.ExecWB WebBrowse ...