ajax+springboot文件上传

ajax+springboot文件上传

前端

<form id="addForm" enctype="multipart/form-data">
								<input class="form-control" type="file" name="files" style="height: 35px;">
								<input id="solution" name="solution" class="form-control" type="text" style="">
								<button type="submit" class="btn btn-primary" onclick="scfile()" style="margin:2%">上传</button>
							</form>
function scfile(){
		var formData = new FormData($("#addForm")[0]);
 		$.ajax({
 			url: "${ctx}/PromeasureList/loadfile", // 文件上传接口
 			type:'post',
 			data:formData,
 			processData: false,
 			contentType:false,
 			success:function (data) {
				$.ajax({
					url:"${ctx}/PromeasureList/updatepath",
					type:"post",
					data:{
						"mainId":$("#solution").val(),
						"daliantype":daliantype,
						"filepath":data
					},
					async:false,
					success:function(data){
						if(data == "200"){
							$("#myModal4").modal("hide");
							load();
						}
					}
				})
 			},
 			error:function () { }
 		});
 	}

后端

//文件上传loadfile
	@RequestMapping(value = { "/loadfile" }, method = RequestMethod.POST)
	@ResponseBody
	public String loadfile(HttpServletRequest request, @RequestParam("files") MultipartFile files) throws IOException {
		Date date = new Date();
		String strDateFormat = "yyyy-MM-dd";
		SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);

		String fileName = sdf.format(date)+ files.getOriginalFilename();
		String filepath = "D:\\fileSource\\autopathfile\\"+fileName;
		File file = new File(filepath);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		if(!files.isEmpty()){
			byte [] bytes = files.getBytes();
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File(filepath)));
			bufferedOutputStream.write(bytes);
			bufferedOutputStream.close();
		}
		return filepath;
	}


	//更新文件路径
    @RequestMapping(value = { "/updatepath" }, method = RequestMethod.POST)
    @ResponseBody
	public String updatepath(ModelMap model,HttpServletRequest request) {
    	String table_name = "dptestinfomain_"+ request.getParameter("daliantype");
    	String id = request.getParameter("mainId");
    	String filepath = request.getParameter("filepath");
    	String aaa = "UPDATE "+table_name+" SET autofilepath = '"+filepath+"' WHERE id = '"+id+"'";
    	try{
			promeasReportServ.BatchEditInfo(aaa);
		}catch (Exception e){
    		e.printStackTrace();
		}
		return "200";
	}

大佬勿喷,欢迎提意见建议评论!!!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js 和 SpringBoot 结合可以构建一个强大的后端服务和前端用户界面,用于实现图片上传功能。这里是一个简要的步骤概述: 1. **前端(Vue)**: - 使用 Vue CLI 创建一个新的项目,并安装必要的依赖,如 `axios` (用于发送 HTTP 请求) 和 `vue-file-upload` 或者 `iview` 这样的 UI 组件库中的文件上传组件。 - 在 HTML 元素上创建一个表单,包含一个文件输入元素 `<input type="file">`,这将让用户选择要上传的图片。 - 使用 JavaScript 视图层代码监听文件输入事件,当用户选择文件后,发送 AJAX 请求到 SpringBoot 后台。 ```javascript <template> <div> <button @click="uploadFile">上传图片</button> <img :src="imageUrl" v-if="imageUrl"> </div> </template> <script> export default { data() { return { imageUrl: '', }; }, methods: { uploadFile() { const file = this.$refs.fileInput.files; // 发送请求到SpringBoot接口 axios.post('/api/upload', { file }, { headers: {'Content-Type': 'multipart/form-data'} }) .then(response => { this.imageUrl = response.data.url; // 存储上传后的图片 URL }); }, }, }; </script> ``` 2. **后端(SpringBoot)**: - 在 SpringBoot 应用中,创建一个 RESTful API 接口,例如 `/api/upload`,用于处理图片上传。使用 Spring MVC 或 Spring WebFlux 来处理HTTP请求。 - 实现图片存储逻辑,通常会使用文件系统、云存储服务或第三方库如 Amazon S3、Google Cloud Storage。 ```java @PostMapping("/upload") public ResponseEntity<String> handleImageUpload(@RequestParam("file") MultipartFile file) throws IOException { try { // 将文件保存到服务器或云存储 String filePath = saveUploadedFile(file); return ResponseEntity.ok("http://your-server/" + filePath); // 返回存储后的图片URL } catch (Exception e) { log.error("Error uploading file", e); throw new RestResponseEntity(HttpStatus.BAD_REQUEST, "图片上传失败"); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值