【Spring】文件上传

时间:2023-02-12 19:56:49

一:引入所需jar包

// https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload
compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.1'
// https://mvnrepository.com/artifact/commons-io/commons-io
compile group: 'commons-io', name: 'commons-io', version: '2.4' 二:配置文件application.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"/>
</bean> 三:编写后台
@RequestMapping(value = "/licenseUpload")
@ResponseBody
public JSONObject licenseUpLoad(@RequestParam("file") MultipartFile file) { JSONObject jsonObject = new JSONObject();
//判断文件是否为空
if (!file.isEmpty()) {
String uploadUrl = PropertyUtil.getValue("upload.url"); // 获取存放路径,可自定义
String fileName = file.getOriginalFilename(); //获取文件名称
try {
file.transferTo(new File(uploadUrl + "//" + fileName));
jsonObject.put("status", 1);
} catch (IOException e) {
jsonObject.put("status", e.getMessage());
ExceptionUtil.showExceptionMessage(e);
}
} else {
jsonObject.put("status", "未上传文件");
} return jsonObject;
}

 四:前端

<form action="http://localhost:8080/license/licenseUpload" method="post" enctype="multipart/form-data">
选择文件:
<input type="file" name="file">
<br/>
<button type="submit" value="提交">
</form>