当我们开发一个Web系统时,常常需要实现上传用户身份证照片或其他图片的功能,上传图片只是上传文件的特殊场景。
使用SpringBoot实现上传文件的功能,非常简单。下面给出一个完整的实现样例。
使用IDEA创建file_uploader模块,创建时使用Spring Web和Lombok依赖,创建后的代码视图如下:
建立controller包,然后在controller包中增加FileController类,现在代码视图变为:
FileController类中有一个upload方法,用于接收来自浏览器的文件,并保存在服务器的static目录中。FileController类的完整源代码如下:
package com.flying.file_uploader.controller;
import lombok.extern.slf4j.Slf4j;
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 javax.servlet.http.HttpServletRequest;
import java.io.File;
@Slf4j
@RestController
public class FileController{
@PostMapping("/upload")
public String upload(@RequestParam(value="upload", required=false)MultipartFile multipartFile, HttpServletRequest httpServerletRequest){
String filePath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
if (filePath.endsWith(".jar")){
int lastSeperator = filePath.lastIndexOf("/");
filePath = filePath.substring(0, lastSeperator);
}
filePath = filePath + "/resource/static";
String fileName = multipartFile.getOriginalFilename();
File directory = new File(filePath);
if (!directory.isDirectory()){
directory.mkdirs();
}
try{
multipartFile.transferTo(new File(filePath, fileName));
return "success";
}catch(Exception ex){
ex.printStackTrace();
}
return "failed";
}
}
修改配置文件application.properties,设置Web服务器的监听端口和静态文件访问路径:
server.port=8070
spring.mvc.static-path-pattern=/static/**
spring.web.resources.static-locations=classpath:/static/
这个HTML页面共用户选择文件,并提供上传按钮:
上传文件
将HTML文件保存为file_uploader.html。
编译服务器程序之后运行,情况如下:
使用浏览器打开file_uploader.html文件,显示如下:
选择要上传的文件(这里准备了一个图片文件apple.jpg),然后点击确定按钮,浏览器显示如下:
在浏览器中,输入apple.jpg文件在服务器的网址,可以看到我们成功地上传了apple.jpg文件:
我们在服务器上查看,resource/static目录中确实有上传的apple.jpg文件:
页面更新:2024-03-13
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号