app对接的项目中图片上传的方式

本文介绍了两种Java Web环境下实现图片上传的方法,一种是通过APP上传用户头像,并将其保存到服务器;另一种是从后台发布图片,涉及到图片的更新及旧图片的删除。文中详细展示了如何获取图片、设置保存路径、处理文件上传异常等关键步骤。

第一种方式:是app传过来的图片



public Object register(Users us,
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request) {
			String[] str = file.getContentType().split("/");
			String path = request.getSession().getServletContext()
					.getRealPath("portrait");
			String fileName = new Date().getTime() + "." + str[1];
			File targetFile = new File(path, fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			try {
				file.transferTo(targetFile);// 保存文件
			} catch (Exception e) {
				e.printStackTrace();
			}
			String basePath = request.getScheme() + "://"
					+ request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath() + "/";
		us.setUsimg(basePath + "portrait/" + fileName);
	}



第二种后台发布的图片


	public String update(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request) {
		if (!file.isEmpty()) {
			String path = request.getSession().getServletContext()
					.getRealPath("carphoto");
			String[] str = file.getContentType().split("/");

			String fileName = new Date().getTime() + "." + str[1];
			File targetFile = new File(path, fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			try {
				InetAddress addr = InetAddress.getLocalHost();
				file.transferTo(targetFile);// 保存文件

				String basePath = request.getScheme() + "://"
						+ addr.getHostAddress().toString() + ":"
						+ request.getServerPort() + request.getContextPath()
						+ "/";
				String img2 = phh.getPhimg();
				String path1 = request.getServletContext().getRealPath("")
						+ img2.substring(img2.indexOf("xxxxx/") + 5);
				File fif = new File(path1);
				if (fif.exists()) {
					fif.delete();
				}
				phh.setPh_img(basePath + "carphoto/" + fileName);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
两种方式残生的图片地址   
http://192.168.0.119:8080/XXXXX/portrait/1488962605223.png

### 使用 Ant Design Vue 实现图片上传 为了在 Vue 项目中利用 Ant Design Vue 组件库实现图片上传功能,需遵循特定配置流程并编写相应代码。 #### 安装依赖包 首先,在项目根目录执行命令安装 `ant-design-vue` 及其相关依赖项。这一步骤确保开发环境具备所需资源来加载和渲染 Ant Design 的组件[^2]。 ```bash npm install ant-design-vue --save ``` #### 配置全局引入 接着,在项目的入口文件 `main.js` 中按如下方式依次导入整个组件库及其默认样式: ```javascript import { createApp } from 'vue'; import App from './App.vue'; // 引入组件库 import antd from 'ant-design-vue'; // 引入样式表 import 'ant-design-vue/dist/antd.css'; const app = createApp(App); app.use(antd); // 注册所有组件 app.mount('#app'); ``` #### 创建上传组件实例 定义一个新的单文件组件用于处理具体的上传逻辑。此部分展示了如何设置 `<a-upload>` 标签属性以及关联事件处理器函数,从而构建一个简易却实用的图像上传界面[^5]。 ```html <template> <div id="uploader"> <!-- 图片卡片形式展示 --> <a-upload name="avatar" listType="picture-card" class="img-upload" :multiple="false" :beforeUpload="handleBeforeUpload" :customRequest="handleCustomRequest" :fileList="imageFiles" @preview="handlePreview" @change="handleChange" @remove="handleRemove" > <div v-if="imageFiles.length < 1"> <a-icon type="plus"/> <div>点击上传</div> </div> </a-upload> <!-- 查看大图模态框 --> <a-modal :visible="modalVisible" footer="" @cancel="closeModal"> <img alt="预览" style="width: 100%" :src="currentImageUrl"/> </a-modal> </div> </template> <script lang="ts"> export default { data() { return { imageFiles: [], // 存储已选中的文件列表 modalVisible: false, // 控制查看器显示状态 currentImageUrl: '', // 当前正在查看的大图链接 }; }, methods: { handleBeforeUpload(file) { const isValidFileType = file.type.startsWith('image/'); if (!isValidFileType) { this.$message.error(`${file.name} 文件类型不合法`); return false; } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { this.$message.error(`图片 ${file.name} 太大 (超过2MB)!`); return false; } return true; }, async handleCustomRequest(option) { try { let formData = new FormData(); formData.append('file', option.file); await fetch('/api/upload', { method: 'POST', body: formData, }); option.onSuccess?.(); // 成功回调 } catch(error){ console.log(error); option.onError?.(); // 错误回调 } }, handleChange(info) { switch (info.file.status) { case 'uploading': break; case 'done': this.imageFiles.push({...info.file}); break; case 'error': this.$message.error(`${info.file.name} 上传失败.`); break; } }, handlePreview(file) { this.currentImageUrl = file.url || file.thumbUrl; this.modalVisible = true; }, closeModel() { this.modalVisible = false; }, handleRemove(file) { this.imageFiles = this.imageFiles.filter(item => item.uid !== file.uid); } } }; </script> <style scoped> /* 自定义样式 */ .img-upload .ant-upload-select-picture-card i { font-size: 32px; color: #999; } .img-upload .ant-upload-select-picture-card div { margin-top: 8px; color: #666; } </style> ``` 上述代码片段实现了基本的图片上传功能,并提供了简单的前端验证机制以保证用户体验流畅性。同时,通过自定义请求方法可以灵活对接不同的后端接口完成实际的数据传输操作[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值