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,

 

转载于:https://www.cnblogs.com/mabylove/p/7397466.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Security中配置跨域有多种方法。一种常见的方法是使用@CrossOrigin注解或重写addCorsMappings方法配置跨域,但是当项目中引入了Spring Security依赖后,这种配置方式可能会失效。 为了解决这个问题,可以使用Spring Security提供的更专业的跨域方案。首先,需要创建一个继承自WebSecurityConfigurerAdapter的配置类,并重写configure方法。在configure方法中,可以通过调用HttpSecurity对象的cors方法来启用跨域配置。 在cors方法中,可以通过CorsConfigurationSource对象的configurationSource方法配置具体的跨域设置。可以使用CorsConfiguration对象来设置允许的请求头、请求方法和请求来源。此外,还可以设置预检请求的缓存时间。最后,需要将CorsConfiguration对象注册到UrlBasedCorsConfigurationSource对象中。 下面是一个示例的配置类的代码: ```java @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .mvcMatchers("/hello1").permitAll() .anyRequest().authenticated() .and() .formLogin() .and() .cors() // 跨域配置 .configurationSource(configurationSource()); } CorsConfigurationSource configurationSource() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.setAllowedHeaders(Collections.singletonList("*")); corsConfiguration.setAllowedMethods(Collections.singletonList("*")); corsConfiguration.setAllowedOrigins(Collections.singletonList("*")); corsConfiguration.setMaxAge(3600L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", corsConfiguration); return source; } } ``` 通过以上配置,Spring Security会自动应用跨域配置,并且保持其他安全配置不受影响。这种方式可以确保跨域配置在Spring Security过滤器之前生效,避免了跨域配置失效的问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Spring Security(七) ——跨域配置](https://blog.csdn.net/tongkongyu/article/details/125982927)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值