vue+springboot图⽚上传和显⽰的⽰例代码⼀、前⾔
在使⽤spring boot做后台系统,vue做前端系统,给客户开发⼀套系统时候,其中⽤到了图⽚上传和显⽰的功能。⼆、环境
前端:vue
前端组件:tinymce
后台:spring boot:2.2.3
三、正⽂
在客户开发⼀套门户管理系统时,集成了tinymce组件,⽤于编辑内容,springboot不同于其他项⽬。
是集成tomcat的,⽂件和图⽚是不能直接访问的。所以我在做集成富⽂本编辑器时,需要处理图⽚的问题。
这个问题跟上传头像等显⽰图⽚的功能是类似的。下⾯记录详情步骤代码。
第⼀步:集成tinymce组件
<!--引⼊tinymce组件-->
import Tinymce from '@/components/Tinymce'
<!--启⽤tinymce组件-->
<el-form-item>
<el-button type="primary" :loading="btnLoading" @click="onSubmit" >保存</el-button>
</el-form-item>
<!--核⼼代码-->
<template>
<div class="page-container">
<div class="page-title-section">
</div>
getsavefilename
<div class="page-content-section">
<div class="page-content-form">
<el-form ref="dataForm" :model="formData" :rules="formRules" label-width="180px">
<el-form-item>
<div>
<tinymce v-model="t" :height="300" />
</div>
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="btnLoading" @click="onSubmit" >保存</el-button>
</el-form-item>
</el-form>
</div>
</div>
</div>
</template>
<script>
import Tinymce from '@/components/Tinymce'
export default {
name:"contentEdit",
components: {Tinymce},
data(){
return{
formData:{
content:'',
},
}
},
created() {
},
mounted() {},
activated() {},
deactivated() {},
methods:{
//表单提交
onSubmit(){
this.$refs['dataForm'].validate((valid) => {
if (valid) {
this.btnLoading = true
this.$axios({
url: this.formData.id == '' ? '/products/save' : '/products/edit',
method: 'POST',
params: this.formData
}).then(res => {
/
/处理成功回调
const{ state,result , errmsg} = res.data
if( state && state == 1 ){
this.$message.success('操作成功');
this.$router.push( {path:'/products/list'} )
}else{
return this.$(errmsg || '操作失败');
}
}).finally(() => {
this.btnLoading = false
})
}
})
},
</script>
<!--Tinymce初始化代码-->
initTinymce() {
const _this = this
window.tinymce.init({
selector: `#${this.tinymceId}`,
language: this.languageTypeList['en'],
height: this.height,
body_class: 'panel-body ',
object_resizing: false,
toolbar: lbar.length > 0 ? lbar : toolbar,
menubar: ubar,
plugins: plugins,
end_container_on_empty_block: true,
powerpaste_word_import: 'clean',
code_dialog_height: 450,
code_dialog_width: 1000,
advlist_bullet_styles: 'square',
advlist_number_styles: 'default',
imagetools_cors_hosts: ['www.tinymce', 'codepen.io'],
default_link_target: '_blank',
link_title: false,
nonbreaking_force_tab: true, // inserting nonbreaking space need Nonbreaking Space Plugin
//上传图⽚回调
images_upload_handler:(blobInfo, success, failure) => {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '/api/file/imageUpload');
var json;
if (xhr.status !== 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.sponseText);
// console.log(json);
json.location = util.baseURL + json.data.filename; //在该位置,如果您的后端⼈员返回的字段已经包含json.location信息,则该处可以省略 if (!json || typeof json.location !== 'string') {
failure('Invalid JSON: ' + sponseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
},
init_instance_callback: editor => {
if (_this.value) {
editor.setContent(_this.value)
}
_this.hasInit = true
<('NodeChange Change KeyUp SetContent', () => {
this.hasChange = true
this.$emit('input', Content())
})
},
setup(editor) {
<('FullscreenStateChanged', (e) => {
_this.fullscreen = e.state
})
}
// 整合七⽜上传
/
/ images_dataimg_filter(img) {
// setTimeout(() => {
// const $image = $(img);
// $veAttr('width');
// $veAttr('height');
// if ($image[0].height && $image[0].width) {
// $image.attr('data-wscntype', 'image');
// $image.attr('data-wscnh', $image[0].height);
// $image.attr('data-wscnw', $image[0].width);
// $image.addClass('wscnph');
// }
/
/ }, 0);
// return img
// },
// images_upload_handler(blobInfo, success, failure, progress) { // progress(0);
// const token = _this.$ken;
// getToken(token).then(response => {
// const url = response.data.qiniu_url;
// const formData = new FormData();
// formData.append('token', response.data.qiniu_token);
// formData.append('key', response.data.qiniu_key);
// formData.append('file', blobInfo.blob(), url);
/
/ upload(formData).then(() => {
// success(url);
// progress(100);
// })
// }).catch(err => {
// failure('出现未知问题,刷新页⾯,或者联系程序员')
// console.log(err);
// });
// },
})
},
destroyTinymce() {
const tinymce = (this.tinymceId)
if (this.fullscreen) {
}
if (tinymce) {
tinymce.destroy()
}
},
setContent(value) {
(this.tinymceId).setContent(value)
},
getContent() {
(this.tinymceId).getContent()
},
imageSuccessCBK(arr) {
const _this = this
arr.forEach(v => {
(_this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`)
})
}
}
第⼆步:后台代码
@RequestMapping(value = "/imageUpload", method = RequestMethod.POST)
public void imageUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
try {
logger.info("上传图⽚名 :" + OriginalFilename());
if (!file.isEmpty()) {
// Properties p = new Properties();// 属性集合对象
// String path = ClassLoader().getResource("").getPath()+"global.properties";
// FileInputStream fis = new FileInputStream(path);// 属性⽂件输⼊流
// p.load(fis);// 将属性⽂件流装载到Properties对象中
// fis.close();// 关闭流
// String uploadPath = p.getProperty("imgUpload.url");
// //路径名称上加上-年/⽉⽇:yyyy/MMdd
// uploadPath += "Uploads/"+new SimpleDateFormat("yyyy").format(new Date())+ "/" +new SimpleDateFormat("MMdd").format(new Date())+"/"; String path= ServletContext().getRealPath("/");
path="/Users/qinshengfei/fsdownload";
<("path:"+path);
//路径名称上加上-年/⽉⽇:yyyy/MMdd
String uploadPath = File.separatorChar+"Uploads"+File.separatorChar+new SimpleDateFormat("yyyy").format(new Date())+
File.separatorChar +new SimpleDateFormat("MMdd").format(new Date())+File.separatorChar;
// ⽂件上传⼤⼩
long fileSize = 10 * 1024 * 1024;
//判断⽂件⼤⼩是否超过
if (Size() > fileSize) {
backInfo(response, false, 2, "");
return;
}
//获取上传⽂件名称
String OriginalFilename = OriginalFilename();
//获取⽂件后缀名:如jpg
String fileSuffix = OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.("image").split(",")).contains(fileSuffix)) {
backInfo(response, false, 3, "");
return;
}
//判断是否有⽂件上传
// if (!ServletFileUpload.isMultipartContent(request)) {
// backInfo(response, false, -1, "");
// return;
// }
// 检查上传⽂件的⽬录
File uploadDir = new File(path+uploadPath);
System.out.println(path+uploadPath);
if (!uploadDir.isDirectory()) {
if (!uploadDir.mkdirs()) {
backInfo(response, false, 4, "");
return;
}
}
// 是否有上传的权限
if (!uploadDir.canWrite()) {
backInfo(response, false, 5, "");
return;
}
/
/ 新⽂件名-加13为随机字符串
String newname = getRandomString(13) +"." + fileSuffix;
File saveFile = new File(path+uploadPath, newname);
try {
backInfo(response, true, 0, uploadPath+newname);
} catch (Exception e) {
<(e.getMessage(), e);
backInfo(response, false, 1, "");
return;
}
} else {
backInfo(response, false, -1, "");
return;
}
} catch (Exception e) {
<(e.getMessage());
}
}
// 返回信息
private void backInfo(HttpServletResponse response, boolean flag, int message, String fileName) {
place("\\","/");
String json = "";
if (flag) {
json = "{ \"status\": \"success";
} else {
json = "{ \"status\": \"error";
}
json += "\",\"fileName\": \"127.0.0.1:8090/file/show?fileName=" + fileName + "\",\"message\": \"" + message + "\"}"; try {
response.setContentType("text/html;charset=utf-8");
} catch (IOException e) {
<(e.getMessage(), e);
}
}
第三步:后台处理显⽰图⽚
/**
* 显⽰单张图⽚
* @return
*/
@RequestMapping("/show")
public ResponseEntity showPhotos(String fileName){
try {
String path = "/Users/qinshengfei/fsdownload";
/
/ 由于是读取本机的⽂件,file是⼀定要加上的, path是在application配置⽂件中的路径
<("showPhotos:"+path+fileName);
return ResponseEntity.Resource("file:" + path + fileName));
} catch (Exception e) {
Found().build();
}
}
第四步:显⽰效果
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论