作者:qw874515 | 来源:互联网 | 2023-10-11 19:46
在平时的业务场景中,避免不了,要搭建文件上传服务器,作为公共服务。一般情况,只做了单个文件的上传,实际业务场景中,却发现单个文件上传,并不能满足一些业务需求,因此我们需要解决如何写一个同时上传多个文件的借口,并返回可下载的文件地址;
废话不多讲,不再从头建立一个Spring boot
项目,如果不知道的话,请直接前往官网查看实例。
下面我们以上传图片为例,示例相对简单,仅供参考:
1 后端上传图片接口逻辑
UploadController.java
package com.zz.controllers.fileUpload;import com.zz.Application;
import com.zz.model.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.*;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.UUID;import static com.zz.config.ConfigConstants.getFileDir;@RestController
@Configuration
public class UploadController {private static final Logger log &#61; LoggerFactory.getLogger(Application.class);&#64;Value("${server.port}")private String port;public String getIp() {InetAddress localhost &#61; null;try {localhost &#61; Inet4Address.getLocalHost();} catch (Exception e) {log.error(e.getMessage());e.printStackTrace();}return localhost.getHostAddress();}&#64;PostMapping(value &#61; "/upload", consumes &#61; {"multipart/form-data"})public Response upload(&#64;RequestParam("file") MultipartFile[] files, Response response) {log.info("上传多个文件");StringBuilder builder &#61; new StringBuilder();String fileAddress &#61;"http://"&#43; getIp()&#43; ":" &#43; port &#43; File.separator;ArrayList<String> imgUrls &#61; new ArrayList<String>();try {for (int i &#61; 0; i < files.length; i&#43;&#43;) {String fileName &#61; files[i].getOriginalFilename();String generateFileName &#61; UUID.randomUUID().toString().replaceAll("-", "") &#43; fileName.substring(fileName.lastIndexOf("."));String distFileAddress &#61; fileAddress &#43; generateFileName;builder.append(distFileAddress&#43;",");imgUrls.add(distFileAddress);files[i].transferTo(new File(getFileDir() &#43; generateFileName));}} catch (Exception e) {e.printStackTrace();}response.setMsg("success");log.info(builder.toString());response.setData(imgUrls);return response;}
}
相对于单个文件的接收&#xff0c;我们这里直接接受多个file
对象&#xff0c;然后遍历生成每个对应的地址。
其中&#xff1a;
getFileDir 设置存放图片的地址&#xff0c;我选择存在项目外的其他地方
com.zz.config.ConfigConstants.getFileDir
package com.zz.config;public class ConfigConstants {public static String fileDir;public static String getFileDir() {fileDir &#61; "/Users/wz/projects/blog/uploadFile/";return fileDir;}
}
当我们把文件生成到指定的文件夹后&#xff0c;我们如何配置在当前server下访问项目外的静态文件图片资源呢&#xff1f;
这个我们就要利用spring boot配置文件 application.yml,
当前还有其他方法比如 WebMvcConfigurer
这里不再赘述。
application.yml
pring:jpa:show-sql: truehibernate:ddl-auto: updateservlet:multipart:max-file-size: 10MBmax-request-size: 10MBprofiles:active: devmvc:static-path-pattern: /**resources:static-locations: file:/Users/wz/projects/blog/uploadFile/,classpath:/static/,classpath:/resources/,classpath:/file/,classpath:/templates/server:use-forward-headers: truetomcat:remote-ip-header: X-Real-IPprotocol-header: X-Forwarded-Proto
my:tokenURL: "55555"authURL: "88888"
后端逻辑已经很清晰&#xff1b;
那前端如何向后端同时发送多个file
对象呢&#xff1f;
2 前端多个文件上传如何传参
html
<input type&#61;"file" multiple class&#61;"el-upload" accept&#61;"image/*" name&#61;"file">
js
var uploadBtn &#61; document.querySelector(&#39;.el-upload&#39;);uploadBtn.onchange &#61; function (e) {let files &#61; this.files;console.log(this.files);const xhr &#61; new XMLHttpRequest();xhr.open("post", "/upload", true);xhr.onreadystatechange &#61; function () {if (this.readyState &#61;&#61;&#61; XMLHttpRequest.DONE && this.status &#61;&#61;&#61; 200) {console.log(JSON.parse(this.responseText));const {data} &#61; JSON.parse(this.responseText);if(!data) return;const imageList &#61; data.slice(0);let imageStr &#61; &#39;&#39;;imageList.forEach(img&#61;>{imageStr &#43;&#61; &#96;${img}" />&#96;;});document.getElementById("result").innerHTML &#61; imageStr;}};const formData &#61; new FormData();if(files && files.length){for (let i&#61;0;i<files.length;i&#43;&#43;) {formData.append("file", files[i])}}console.log(formData);xhr.send(formData);
};
前端通过FormData
传参数发送POST请求&#xff1b;
区别于之前的单个formData.append();
这里我们可以同时append
多个相同名字的文件二进制文件流&#xff1b;
![image-20191123234150228](assets/image-
.png)
如图结果正常显示&#xff0c;当我们部署到服务器的时候&#xff0c;这个就可以当作一个web服务器供大家使用。
本章完结&#xff01;