9

Java文件上传实例并解决跨域问题

 3 years ago
source link: https://blog.csdn.net/promsing/article/details/120089365
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Java文件上传实例并解决跨域问题

专栏收录该内容
3 篇文章 1 订阅

Java文件上传实例并解决跨域问题

目录

了解MultipartFile接口

文件上传业务代码

Controller类

Service类:写了具体的业务逻辑

修改nginx配置,将文件存储到文件服务器中

每次上传文件都会经过网关,必然会给网关带来很大的压力,那我们如何绕过网关呢?

1.在网关中配置白名单 ,这样也会走网关,只是压力少了一点点

2.在nginx做转发,当请求文件上传时,直接转到相应的服务

解决上传文件出现跨域问题

写配置类CorsFilter

在nginx配置中配置请求实体大小


在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传功能的实现。

了解MultipartFile接口

我们实现文件的上传用到了Spring-web框架中的 MultipartFile接口,MultipartFile接口的源码注释中说“MultipartFile接口是  在大部分请求中接收的上载文件的表示形式。”

A representation of an uploaded file received in a multipart request.
The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storage will be cleared at the end of request processing.

常用方法如下表

Method Summary byte[]获取文件的字节数组getBytes()
          Return the contents of the file as an array of bytes. String获取文件的类型getContentType()
          Return the content type of the file. InputStream获取文件的输入流getInputStream()
          Return an InputStream to read the contents of the file from. String获取文件名getName()
          Return the name of the parameter in the multipart form. String获取原始文件名(防止篡改文件类型)getOriginalFilename()
          Return the original filename in the client's filesystem. long获取文件的大小,以字节的形式)getSize()
          Return the size of the file in bytes. boolean判断文件是否为空isEmpty()
          Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content. void将接收到的文件传输到给定的目标文件。transferTo(File dest)
          Transfer the received file to the given destination file.

文件上传业务代码

Controller类

Service类:写了具体的业务逻辑

修改nginx配置,将文件存储到文件服务器中

修改Nginx的配置文件nginx.conf,监听80端口,设置root的值为:E盘

- 图片不能保存在服务器内部,这样会对服务器产生额外的加载负担
- 一般静态资源都应该使用独立域名,这样访问静态资源时不会携带一些不必要的cookie,减小请求的数据量

每次上传文件都会经过网关,必然会给网关带来很大的压力,那我们如何绕过网关呢?

1.在网关中配置白名单 ,这样也会走网关,只是压力少了一点点

2.在nginx做转发,当请求文件上传时,直接转到相应的服务

本实例使用了方法二、需要增加配置

当这样配置之后,文件上传就不会过网关,减少了网关的压力。但是有引来了一个新问题那就是跨域。

解决上传文件出现跨域问题

由于Nginx将文件上传的请求直接转发到了具体服务中,不再走gateway,所以gateway中的跨域配置,不再生效了。 需要在文件上传这个服务中单独配置跨域。

写配置类CorsFilter

到此应该就可以上传了,但是还是报跨域,我已经配置好了啊,为什么还是报跨域呢?

在nginx配置中配置请求实体大小

我就想是不是Nginx的问题,然后我就一行一行的读配置,最后发现

nginx配置中没有配置请求实体大小

image.png

加上这行配置就好了

client_max_body_size 1024m;

如果本篇博客对您有一定的帮助,大家记得留言+点赞+收藏哦。 


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK