参考文献:https://www.cnblogs.com/wryd952532573/p/7509428.html
Step1:表单设置为post提交方式,并在表单中加入enctype="multipart/form-data"
<form id="fm" method="post" enctype="multipart/form-data">
<input type="file" name="scriptFile" style="width:169px;"/>
</form>
如果少了这个声明,可能会报错:Cannot convert value of type [java.lang.String] to required type [org.springframework.web.multipart.MultipartFile] for property 'xxxxx': no matchi
Step2:配置文件中设置MultipartResolver
<!-- 文件上传大小 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!-- 所有文件容量之和不超过10M -->
<property name="maxUploadSize" value="10000000" />
<property name="maxInMemorySize" value="40960" />
</bean>
Step3:Controller接受参数
@RequestMapping("/insert")
public String insert(HttpServletResponse response, HttpServletRequest request,
DeviceModel deviceModel)
throws Exception
{
JSONObject result = new JSONObject();
if (deviceModel.getScriptFile() != null){
String tmpName = deviceModel.getScriptFile().getOriginalFilename();// 原始文件名
String fileName = StringUtil.getFileName()+tmpName.substring(tmpName.indexOf("."));//构造文件名
String path = request.getServletContext().getRealPath("/upload/imgs/deviceModel/");
//获取指定文件或文件夹在工程中真实路径,getRequest()这个方法是返回一个HttpServletRequest,封装这个方法为了处理编码问题
FileOutputStream fos = FileUtils.openOutputStream(new File(path+"/" +fileName));//打开FileOutStrean流
IOUtils.copy(deviceModel.getScriptFile().getInputStream(),fos);//将MultipartFile file转成二进制流并输入到FileOutStrean
fos.close();//
}
...
其中,DeviceModel实体类定义如下:
public class DeviceModel
{
private MultipartFile scriptFile;
...
来源:CSDN
作者:pang9998
链接:https://blog.csdn.net/pang9998/article/details/104518132