FormData implementation file upload example



The front end here uses easy-ui filebox

Front-end code


<%@ 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>


attributes of the model class

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 ;


Code behind

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;
	}
}

To sum up: because ordinary form submission cannot pass the file attribute, formdata is used to pass it 
Use the append method of formdata to add the parameters to be uploaded, and the background will automatically encapsulate the corresponding entity class with an entity receiving 
Finally reuse
FileUtils.copyInputStreamToFile(myfile.getFile().getInputStream(), new File("G:/upload/", myfile.getFile().getOriginalFilename()));
This method uploads the corresponding file to the corresponding directory

Guess you like

Origin blog.csdn.net/a447332241/article/details/78848504