MultipartFile 文件上传

Spring Boot + Html + FormDate 实现参数和文件同时提交

前台页面 + JS

<form>
   <input type="file" name="file" id="file_id">
   <input type="button" value="上传文件" onclick="upload_file();">
</form>

点击触发上传事件

function upload_file(){
    let formDate = new FormData();
    formDate.append("fileName","userInfo.doc");
    formDate.append("dateTime",new Date().getTime().toString());
    formDate.append("file",$("#file")[0].files[0]);
    $.ajax({
        url: basePath + "/file/upload",
        type:"POST",
        data:formDate,
        cache: false,
        processData: false,  //不使用默认序列化
        contentType: false,  //不使用默认数据格式化
        success:function(result){
			alert(result.msg);
        }
    });
}
cache: false

不使用缓存

processData: false

默认为 true 将对象以字符串形式传输 ,此处不使用默认序列化, 直接使用 FormDate数据格式提交

contentType: false

默认值 : application/x-www-form-urlencoded , 次处不使用默认数据格式, 以此来满足文件对象传输

后台接收

 package com.spring.login.controller;

import com.spring.login.model.FileBean;
import com.spring.login.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping(value = "file")
public class FileController {

@Autowired
private FileService fileService;

@PostMapping(value = "upload")
public void uploadFile(FileBean fileBean, @RequestParam(value = "file",required = false) MultipartFile file){
    System.out.println("文件名:" + file.getOriginalFilename());
    FileInputStream inputStream = null;
    try {
        inputStream = (FileInputStream) file.getInputStream();
        fileService.upload(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if ( null != inputStream ) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38565317/article/details/106885515