上传文件时,如果不选择文件,如何保留原来数据?

8 篇文章 0 订阅
1 篇文章 0 订阅

两种思路:

一种用一个变量保存。


代码如下:

    @Value("#{conf.appendixPath}")
    private String appendixPath;


	/具体添加
	@RequestMapping(value="/projectDetailAdd", method=RequestMethod.POST)
	public ModelAndView orgAdd(ProjectDetail projectDetail,HttpServletRequest request,HttpServletResponse response,@RequestParam(value = "filePath", required = false) MultipartFile file) throws ParseException {
		/*
		 * 1获取参数
		 * 2转换
		 * 3赋值
		 */
		
		
		//获取参数
		

		
		
		//转换



		
		//赋值

		String did = request.getParameter("did");
		if(projectDetail.getDid()==null)
		{
			projectDetailService.add(projectDetail);
			//上传文件
			if (file != null && file.getSize() > 0) {
				try {
					String pathString = saveFileToServer(file, appendixPath, "detail_"+projectDetail.getDid());
					
					projectDetail.setPath(pathString);
					
					
					projectDetailService.update(projectDetail);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			
			
		}
		else
		{
			if (file != null && file.getSize() > 0) {
				try {
					String pathString = saveFileToServer(file, appendixPath, "detail_"+projectDetail.getDid());
					
					projectDetail.setPath(pathString);
					
					projectDetailService.update(projectDetail);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			else
			{
				//当文件为空,则保存原来数据
				String pathBack = request.getParameter("pathBack");
				projectDetail.setPath(pathBack);
				
			}
			projectDetailService.update(projectDetail);
			
		}
		
		ModelAndView view =  new ModelAndView("projectDetail", "message", "");
		
		return view;
	}



saveFileToServer方法

	//上传文件
	private String saveFileToServer(MultipartFile multifile, String path, String carId)
		throws IOException {
		// 创建目录
		File dir = new File(path);
		if (!dir.exists()) {
				dir.mkdir();
		}
		// 读取文件流并保持在指定路径
		InputStream inputStream = multifile.getInputStream();
		String fileName = multifile.getOriginalFilename();

		String[] fileNameArr = fileName.split("\\.");

		OutputStream outputStream = new FileOutputStream(path
				+carId +"." + fileNameArr[1]);
		byte[] buffer = multifile.getBytes();
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = inputStream.read(buffer)) != -1) {
			bytesum += byteread;
			outputStream.write(buffer, 0, byteread);
			outputStream.flush();
		}
		outputStream.close();
		inputStream.close();

		return path	+ carId +"." + fileNameArr[1];
}


HTML主要代码

<input name="pathBack" type="text" class="input-style1" id="pathBack" value="${projectDetail.path}" />

<input id="filePath" type="file" name="filePath"/>



另外一种办法从数据库中取出数据保存出来,然后再赋值,最后UPDATE。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值