1. 程式人生 > >Spring上傳File檔案

Spring上傳File檔案

配置檔案:spring-mvc.xml

<!-- 檔案上傳 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="defaultEncoding" value="utf-8" />
</bean>

jsp程式碼:前端框架H-ui

<div class="row cl">
	<label class="form-label col-xs-4 col-sm-3"><span class="c-red">*</span>安裝包路徑:</label>
	<div class="formControls col-xs-8 col-sm-9">
	    <span class="btn-upload form-group">
	        <input class="input-text upload-url" type="text" readonly name="path" id="path">
		<span style="padding-left:10px"><a href="javascript:void();" class="btn btn-primary radius"> 瀏覽檔案</a></span>
	        <input type="file" name="file" id="file" class="input-file">
	    </span>
	</div>
</div>

後臺:

使用【MultipartFile file】接收檔案引數,

// 上傳檔案路徑
String path = this.fileService.getAbsPath() + "/resources/upload/app/";
File imgDir = new File(path);
if (!imgDir.exists())
{
    imgDir.mkdirs(); // 建立儲存目錄
}
if (file != null && !file.isEmpty())
{
    // 上傳檔名
    String filename = file.getOriginalFilename();
    // 將上傳檔案儲存到一個目標檔案當中
    String filePaths = path + UUID.randomUUID().toString().replace("-", "") + "."
                + filename.substring(filename.lastIndexOf('.') + 1);
    file.transferTo(new File(filePaths));
}
此處提供一篇優質的部落格: https://blog.csdn.net/qian_ch/article/details/69258465