• Spring-boot之jQuery File Upload后台配置方法以及前台跨域


    文件上传在Spring-boot中本身配置起来非常简单,但是有个多文件传递和单个传递的问题。

    两者配置是略有不同的,而且还有一些让我这个技术小白很容易踩坑的地方。

    重要的几点:

    上传的是单个文件:  MultipartFile file

    上传的是多个文件: MultipartFile[] file

    先从单个文件上传 后台配置来说:

    public Map uploadFile(@RequestParam("file") MultipartFile file,HttpServletRequest req) { // 注意的是 MultipartFile file 表示上传单个文件
    
    
     File tempFile = new File( 文件上传目录 );
      if (!tempFile.getParentFile().exists()) {
        tempFile.getParentFile().mkdirs();   // 如果没有找到上传的目录就会创建这个目录
      }
    
      if (!file.isEmpty()) { 
    
        try {
          BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));   // 开始上传
    
          out.write(file.getBytes());  
          out.flush();
          out.close();
    
        } catch (FileNotFoundException e) {
    
          e.printStackTrace();
          result.put("msg", "上传文件产生错误," + e.getMessage());
          result.put("result", false);
    
         }  catch (IOException e) {
    
          ....
    
        }
    
      }
    
      return result;
    
    }
    

       

    spring-boot后台完整代码:

     1 import java.io.BufferedOutputStream;
     2 import java.io.File;
     3 import java.io.FileNotFoundException;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.text.SimpleDateFormat;
     7 import java.util.Date;
     8 import java.util.HashMap;
     9 import java.util.Map;
    10 
    11 import javax.servlet.http.HttpServletRequest;
    12 
    13 import org.springframework.beans.factory.annotation.Autowired;
    14 import org.springframework.beans.factory.annotation.Value;
    15 import org.springframework.web.bind.annotation.RequestMapping;
    16 import org.springframework.web.bind.annotation.RequestMethod;
    17 import org.springframework.web.bind.annotation.RequestParam;
    18 import org.springframework.web.bind.annotation.ResponseBody;
    19 import org.springframework.web.bind.annotation.RestController;
    20 import org.springframework.web.multipart.MultipartFile;
    21 
    22 @RestController
    23 @RequestMapping("/upload")
    24 public class UploadFileController {
    25     // 存储文件
    26     @RequestMapping(value = "/uploadFile",method={RequestMethod.POST})
    27     public Map uploadFile(@RequestParam("file") MultipartFile file,HttpServletRequest req) {
    28         Map result = new HashMap<>();
    29         SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式
    30         String dateDir = df.format(new Date());// new Date()为获取当前系统时间
    31         File tempFile = new File(fileDIr + dateDir + File.separator
    32                 + file.getOriginalFilename());
    33         
    34         if (!tempFile.getParentFile().exists()) {
    35             tempFile.getParentFile().mkdirs();
    36         }
    37         if (!file.isEmpty()) {
    38             try {
    39                 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
    40                 // "d:/"+file.getOriginalFilename() 指定目录
    41                 out.write(file.getBytes());
    42                 out.flush();
    43                 out.close();
    44             } catch (FileNotFoundException e) {
    45                 e.printStackTrace();
    46                 result.put("msg", "上传文件产生错误," + e.getMessage());
    47                 result.put("result", false);
    48             } catch (IOException e) {
    49                 e.printStackTrace();
    50                 result.put("msg", "上传文件产生错误," + e.getMessage());
    51                 result.put("result", false);
    52             }
    53             result.put("msg", "上传成功");
    54             result.put("result", true);
    55         } else {
    56             result.put("msg", "上传文件为空");
    57             result.put("result", false);
    58         }
    59         return result;
    60     }
    61 }
    View Code

    这段代码可以直接放到spring-boot中跑,


    再从多个文件上传 后台配置来说:

    jQuery File Upload 就是一个支持多文件上传插件,这个时候如果继续调用上面的单文件上传的接口就直接前台报错啦,当然还有其他的原因。

    注意以下几点就好:

    1. 由于是多文件,所以上传过来的是一个数组文件,所以需要用: MultipartFile[] multipartfiles

     2.由于jQuery File Upload的输入框中:<input id="fileupload" type="file" name="files[]" multiple>

       name="files[]"   这个name需要和  @RequestParam(value ="files[]")的value值相等,这样就可以上传文件了。

    完整后台代码

     1 import java.io.File;
     2 import java.util.Map;
     3 
     4 import javax.servlet.http.HttpServletRequest;
     5 import javax.servlet.http.HttpServletResponse;
     6 
     7 import org.springframework.web.bind.annotation.RequestMapping;
     8 import org.springframework.web.bind.annotation.RequestMethod;
     9 import org.springframework.web.bind.annotation.RequestParam;
    10 import org.springframework.web.bind.annotation.RestController;
    11 import org.springframework.web.multipart.MultipartFile;
    12 
    13 @RestController
    14 @RequestMapping("/upload")
    15 public class UploadFileController {
    16     // 存储文件
    17     @RequestMapping(value = "/uploadFile",method={RequestMethod.POST})
    18     public Map uploadFile(@RequestParam(value ="files[]") MultipartFile[] multipartfiles,HttpServletRequest req) {
    19         Map result = new HashMap<>(); 
    20        String savePath = '文件目录';  
    21        if(null != multipartfiles && multipartfiles.length > 0){  
    22            //遍历并保存文件
    23            for(MultipartFile file : multipartfiles){  
    24                file.transferTo(new File(savePath + file.getOriginalFilename()));  
    25            }  
    26        }
    27         result.put("msg", "上传成功");
    28         result.put("result", true);
    29         return result;
    30     }
    31 }
    View Code

    最后说一说前端jQuery File Upload的使用方法:

    放到spring-boot项目下的static目录下面:

     

    这样就可以了,完了....所以使用起来非常的方便

    额,差点忘了,补充一下,通常我们不可能都放在项目目录下,前后端可能是分离开的。

    jQuery File Upload Plugin是支持跨域的!!!

    只需要在上传的文件下面多增加一条配置即可:具体可以看官网  Cross-site iframe transport uploads

     forceIframeTransport: true,

  • 相关阅读:
    HDU 1716 排列2
    HDU 3405 World Islands
    HDU 5624 KK's Reconstruction
    HDU 2689 Tree
    UVA 12075 Counting Triangles
    UVA 11100 The Trip, 2007
    [USACO 2004DEC] Navigation Nightmare
    [USACO 2017DEC] Barn Painting
    [Usaco2017 Dec] A Pie for a Pie
    [USACO 2017DEC] Greedy Gift Takers
  • 原文地址:https://www.cnblogs.com/mabylove/p/7397466.html
Copyright © 2020-2023  润新知