您的位置:首页 > 编程语言 > Java开发

SpringBoot配置文件上传

2017-10-09 14:37 483 查看
注意:默认SpringBoot使用的是Spring本身的上传功能,如需使用apache upload需配置转换器

1、在properties文件中配置文件上传key-value

#默认支持文件上传
spring.http.multipart.enabled =true
spring.http.multipart.file-size-threshold =0
# 上传文件的临时目录
#spring.http.multipart.location=E:/upload/temp/
# 最大支持文件大小
spring.http.multipart.max-file-size =100MB
# 最大支持请求大小
spring.http.multipart.max-request-size =100Mb

2、上传文件代码

@RequestParam
("file"
) file为页面提交过来的字段名,如:<input type="file" name="file"> 对应name值

@Slf4j
@Controller
@RequestMapping("/func" )
public class FunctionController extends BaseController {
@Autowired
private UploadConfig uploadConfig;

@RequestMapping(value = "/uploadFileLocal", method = RequestMethod.POST )
public void uploadFileLocal(@RequestParam ("file" ) MultipartFile file, HttpServletRequest request , HttpServletResponse response ) throws Exception {
JSONObject json = new JSONObject();

String innerCode = request.getParameter("innerCode" );
log.info("开始接收机器innerCode-{}的文件" , innerCode);

if(StringUtils.isEmpty( innerCode)) {
json.put("code" , 500);
json.put("msg" , "机器号innerCode不能为空" );
writeJSON( json, response );
return ;
}

if(file .isEmpty()) {
json.put("code" , 500);
json.put("msg" , "没有上传的文件流" );
writeJSON( json, response );
return ;
}

String fileName = file.getOriginalFilename();
String path = uploadConfig .getReceiveRoot() + "/" + innerCode + "/";
log.info("接收文件保存路径-{},文件大小为-{}" , path , file .getSize());
File localFile = new File(path);

if(!localFile .exists()) {
localFile.mkdirs();
}
try {

file.transferTo(new File(path+fileName));

//downloadUrl为包的下载目录
String downloadUrl = uploadConfig.getReceiveDownloadRoot() + innerCode + "/" + fileName ;
json.put("code" , 200);
json.put("url" , downloadUrl );
log.info("文件{}上传成功" , downloadUrl );
} catch (Exception e ) {
json.put("code" , 500);
json.put("msg" , "上传发生异常" );
log.error("上传文件发生异常,异常信息:" , e );
}
writeJSON( json, response );
}
}

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
@Configuration
public class UploadConfig {

//接收文件服务URL
@Value("${upload.RECEIVE_FILE_URL}")
private String receiveFileUrl;

//接收文件目录
@Value("${upload.RECEIVE_ROOT}")
private String receiveRoot;

//接收文件下载根域名地址
@Value("${upload.RECEIVE_DOWNLOAD_ROOT}")
private String receiveDownloadRoot;

//上传根目录
@Value("${upload.UPLOAD_ROOT}")
private String uploadRoot;

//下载根域名地址
@Value("${upload.DOWNLOAD_ROOT}")
private String downloadRoot;

//文件后缀
@Value("${upload.SUFFIXLIST}")
private String suffixList;

public String getParentPath( int index ) {
if(index == 1) {
return "/uboxsys" ;
} else if (index == 2) {
return "/lua" ;
} else if (index == 3) {
return "/web" ;
} else if (index == 4) {
return "/script" ;
}
return null ;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: