FormData 实现文件上传实例

本文介绍使用EasyUI的FileBox组件实现文件上传的方法。包括前端页面设计、表单数据构造及后端处理流程。利用FormData对象进行文件数据封装,并通过Ajax发送请求,最终借助FileUtils完成文件保存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



这里前端使用了easy-ui的filebox

前端代码


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

  		<h2>文件上传</h2>
	 
	<div style="margin:20px 0;"></div>
	<form id="importFileForm" method="post" enctype="multipart/form-data">  
	<div class="easyui-panel" title="Upload File" style="width:400px;padding:30px 70px 50px 70px">
	<!-- 	<div style="margin-bottom:20px">
			<div>Name:</div>
			<input class="easyui-textbox" style="width:100%">
		</div> -->
		<div style="margin-bottom:20px">
			<div>File1:</div>
			<input class="easyui-filebox" name="fileImport"  id="fileImport" data-options="prompt:'Choose a file...'" style="width:100%">
		</div>
		<!-- <div style="margin-bottom:20px">
			<div>File2:</div>
			<input class="easyui-filebox" name="file2" data-options="prompt:'Choose another file...'" style="width:100%">
		</div> -->
		
		 	<div style="margin-bottom:20px">
			<div>remark:</div>
			<input class="easyui-textbox" style="width:100%" name="remark" id="remark">
		</div>  
		
		<div>
			<a  id="upload" class="easyui-linkbutton" style="width:100%">Upload</a>
		</div>
	</div>
	</form>
<script type="text/javascript">
$("#upload").click(function(){
	 
	importFileClick();
})

function importFileClick()
{
	 
	
	var file = $('input[name="fileImport"][type="file"]').prop('files')[0];
	if( file==null ) {alert("请选择文件");return;}
	//获取文件名称
	var fileName =file.name; 
	//获取文件类型名称  
    var filetype = fileName.substring(fileName.lastIndexOf('.'), fileName.length);
	
    var fileRemakr = $("input[name='remark']").val();  //文件备注
	alert(fileRemakr);
   
    //计算文件大小  
    var fileSize = 0;  
   // //如果文件大小大于1024字节X1024字节,则显示文件大小单位为MB,否则为KB  
    if (file.size > 1024 * 1024) {  
		fileSize = Math.round(file.size * 100 / (1024 * 1024)) / 100;  

		if (fileSize > 10) {  
             alert('错误,文件超过10MB,禁止上传!'); return;  
      	  }  
		fileSize = fileSize.toString() + 'MB';  
 		   }  
    else {  
        fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';  
    }  
	
	  var formData = new FormData();
	  formData.append("file", file);  // 文件对象
	  formData.append("filetype",filetype); //文件类型
	  formData.append("fileName",fileName); //文件名
	  formData.append("fileSize",fileSize); //文件大小
	  formData.append("upLoader", "${USER.realName }");  //文件上传者
	  formData.append("remark", fileRemakr);   //文件备注
	    
    $.ajax({  
        url:"file/upload",  
        type: 'POST',  
        data: formData,
        async: false,  
        cache: false,  
        contentType: false,  
        processData: false,  
        success: function (Msg) {    
        	alert("上传成功");
        	$("#remark").val("");  //清空备注的值
        	$("#fileImport").val("");
        },  
        error: function (Msg) {  
        	alert(XMLHttpRequest.status);
            alert(XMLHttpRequest.readyState);
            alert(textStatus);
               
        }  
    });  
      	
}  

 
</body>
</html>


model类的属性

public class FileTransInfo {
	private String fileName;
	
	private String url;  

	private String upLoader;
	
	private String GroupName;
	
	private String filePath;
	
	private String filetype;
	
	private String type;
	
	private String fileSize;
	
	private String remark;
	
	private MultipartFile file ;


后台代码

package cn.easyproject.easyee.sm.file.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.easyproject.easyee.sm.file.entity.FileInfo;
import cn.easyproject.easyee.sm.file.service.FileService;
import cn.easyproject.easyee.sm.file.vo.FileTransInfo;


@Controller 
@RequestMapping("file")
public class FileController {
	
	@Autowired
	private FileService fileService;
	
	//MultipartFile file
	/**
	 * 文件上传
	 * @param myfile
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	public Map<String, String> UploadFile( FileTransInfo myfile,HttpServletRequest request)
	{
	 Map<String, String> map = new HashMap<>();	
	  FileInfo newfile = new FileInfo();
	  newfile.setFilename(myfile.getFileName());    //文件名
	  newfile.setFilesize(myfile.getFileSize());    //文件大小
	  newfile.setFiletype(myfile.getFiletype());  	//文件类型
	  newfile.setFileuploader(myfile.getUpLoader());  //文件上传人
	  newfile.setFilestate("正常");
	  if(null!=myfile.getRemark())
		  newfile.setRemark(myfile.getRemark());
	  
	  String realPath = "G:/upload/"+myfile.getFileName();   //真实文件地址
	  
	  newfile.setFilepath(realPath);
	  
	  try {
		FileUtils.copyInputStreamToFile(myfile.getFile().getInputStream(), new File("G:/upload/", myfile.getFile().getOriginalFilename()));
		fileService.fileUpload(newfile);
	  } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}
	 System.out.println("结束");
	 map.put("info", "上传成功");
	 return map;
	}
}

总结一下:由于普通的表单提交无法传递file属性  所以要用到formdata来传递 
利用formdata的append方法添加要上传的参数,后台用一个实体接收 会自动封装到相应的实体类中 
最后再利用
FileUtils.copyInputStreamToFile(myfile.getFile().getInputStream(), new File("G:/upload/", myfile.getFile().getOriginalFilename()));
这个方法 将对应的文件上传到相应的目录
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值