您的位置:首页 > 移动开发

ionic4结合ng2-file-upload实现手机端图片上传

2019-02-17 21:21 190 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ldb987/article/details/87558383

上传图片折腾了好几天,终于实现了,记录一下。

1、安装插件 ng2-file-upload ,cnpm install ng2-file-upload --save

2、在需要使用插件的页面的module.ts文件中加入依赖

注意:如果这一步不加入依赖,会出现下面的错误

3、在相应的ts文件中加入依赖,并声明FileUploader类型的变量

import { FileUploader } from 'ng2-file-upload';

// 声明一个FileUploader类型的变量,并将其初始化
public uploader: FileUploader = new FileUploader({
url: this.uploadPictureUrl,
method: 'POST',
// autoUpload: true,
removeAfterUpload: true,
itemAlias: 'multfile'
// allowedFileType: ['image']
});

4、html

<div class="item act-cell-padding" style="height: 160px;">
<span>活动文案:</span>
<div class="picPlace">
<img id="wizardPicturePreview" name="picture" src="{{picture}}" style="height:100px;  width:100px;display:block; border:1px solid #CCC" alt="" class="picture-src" title="" />
<input #file type="file" id="file" class="showPicture"  ng2FileSelect  [uploader]="uploader" (change)="selectedFileOnChanged(file)">
</div>
</div>

5、ts文件中加入change事件,上传图片到fastdfs,然后接受fastdfs返回的图片地址

// 选择上传图片
public selectedFileOnChanged(file: HTMLInputElement) {
let length: number;
this.editPicture = !this.editPicture;
this.fileName = file.value;
const fileDot: string = this.fileName.substring(this.fileName.lastIndexOf('.') + 1, this.fileName.length);

// 开始上传
this.uploader.queue[0].upload();

this.uploader.queue[0].onSuccess = function(response, status, headers) {
// 上传文件成功
if (status === 200) {
// 上传文件后获取服务器返回的数据
const temRes = JSON.parse(response);
let data = temRes.data;
// 修改页面图片
const el: Element = document.getElementById('wizardPicturePreview');
el.setAttribute('src', data);

length = data.length;
data = data.substring(21, length);
this.picture = data;
localStorage.setItem('picUrl', 'http://192.168.22.64/' + data);
} else {
alert('上传图片失败');
}
};
}

6、后端实现图片上传

/**
* saveImage-保存图片
*
* @Params: file 文件
* @author
* @since 0.0.1 2018-8-6 14:43:57
*/
@ApiOperation(value = "上传图片")
@PostMapping(value = {"/upload"})
public IntegralResult<String> uploadImage(@RequestParam(value="multfile",required=false)MultipartFile file) {

try {
String imagePath = medalService.saveImage(file);
return IntegralResult.build(IntegralResult.SUCCESS, "文件:" + file.getName() + "上传成功", imagePath);
} catch (IOException e) {
return IntegralResult.build(IntegralResult.FAIL, "上传失败", e.getMessage());
}
}

注意:@RequestParam(value=“multfile”)需要和new FileUploader中的别名itemAlias: 'multfile’一致,否者后端接收到的file始终都是null

7、需要配置全部cose跨域

private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}

参考链接:SpringBoot配置Cors解决跨域请求问题

注意:初始使用这个方法的时候,没有“ corsConfiguration.setAllowCredentials(true);”这句配置,出现以下错误

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: