java spring mvc 文件上传教程

知识储备

jsp页面加载时<% %>   ,<@  />  ,<c >中的内容先执行;

${ }中的变量被替换成相应的值在页面中。

准备工作

上传使用jquery.fileupload.js,这个是文件的ajax上传,所需的包和依赖文件为1框中的

文件的上传后台对应为FileController.java


导入js文件
<script type="text/javascript" src="<%=path%>/public/js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="<%=path%>/public/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="<%=path%>/public/js/jquery.fileupload.js"></script>


文件上传步骤:

1.jsp代码:

添加file类型的控件,id设为fileupload
<input id="fileupload" type="file" name="file" value="上传数据" style="display:none;">

为了便于获取到页面当中table中的值传到js中,做以下处理:

将点击上传数据的链接添加一个点击事件,触发javascript中的函数
<a href="javascript:void(0);" οnclick="uploadDataFile('${details.interId}')">上传数据</a>
<span style="font-family:SimSun;">定义一个全局变量,将函数uploadDataFile()后的参数赋给这个全局变量。</span>
JavaScript代码如下:
<script type="text/javascript">
	var global_interId;

	function uploadDataFile(interId){
		global_interId = interId;
		$("#fileupload").click();
	}
	$(function() {
		$('#fileupload').fileupload({
	        url: "<%=path%>/file/upload",
	        autoUpload:true,
	        //dataType: 'json',
	        done: function (e, data) {
	        	/*更新上传文件的信息*/
	        	alert(data.result);//data.result中存的是上传文件的路径
	        	var id=$("#innerId").val();
	        	htmlobj=$.ajax({url:"<%=path%>/check/editCheckFile?filename="+data.result+"&id="+global_interId,async:false});      	
	        	var result = htmlobj.responseText;
        	  	if(!result){
        	  		alert("上传错误,请重新上传!");
        	  	}else{
        	  		alert("文件上传成功!")
        	  	}
	        },
	        /* 进度条 */
	        progressall: function (e, data) {
	            /* var progress = parseInt(data.loaded / data.total * 100, 10);
	            $('#progress2 .progress-bar').css('width',progress + '%'); */
	        }
	    }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');
	});
</script>

以上js执行FileController中的内容。

2、FileController.java代码:

package hhd.pmanage.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("file")
public class FileController {
	
	@SuppressWarnings("deprecation")
	@ResponseBody
	@RequestMapping(value="upload")
	public Object upload(@RequestParam(value="file", required=false) MultipartFile file, HttpServletRequest request){
		
		String fileName = file.getOriginalFilename();
		
		String extensions = fileName.substring(fileName.lastIndexOf("."));
		
		fileName = System.currentTimeMillis() + extensions;
		
		File dir = new File(request.getRealPath("/") + "upload");
		if(!dir.exists()){
			dir.mkdirs();
		}
		
		try {
			//文件写入到服务器
			File newFile = new File(dir + "/" + fileName);
			file.transferTo(newFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/upload/"+fileName;
	}
<h2>}
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>


3.自己定义的上传数据库操作:

<span style="font-family: Arial, Helvetica, sans-serif;">htmlobj=$.ajax({url:"<%=path%>/check/editCheckFile?filename="+data.result+"&id="+global_interId,async:false}); </span>

这里的URL是定义上传文件数据库操作要执行的controller。
controller中的代码参考:
//插入文件
	@RequestMapping(value = "editCheckFile", method = RequestMethod.GET)
	public @ResponseBody Object editCheckFile(HttpSession session,
			@RequestParam(value="filename", required=false)String file_name,
			@RequestParam(value="id", required=false)String p_id) throws Exception{
		//插入文件
		FilesModel filesModel=new FilesModel();
		Date day=new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
		
		filesModel.setEnvalue(0);
		filesModel.setFileName(p_id+"_拆检报告"+df1.format(day));
		filesModel.setFileType(0);//0拆检报告
		filesModel.setpId(p_id);
		
		filesModel.setTime(df.format(day));
		filesModel.setUrl(file_name);
		
		int flag=fileService.addFile(filesModel);
		logService.addLogs(session,"拆检模块","上传拆检报告文件", "上传了内部编号为"+p_id+"的产品的拆检报告");//操作日志
		if(flag==0){
			return true;
		}
		return false;
	}




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值