在web開發中,常常會遇到上傳文件的需求,比如上傳視頻和圖片,之前做上傳功能的時候,就是使用IO流來操作,這種需要熟悉IO各種輸入輸出流,當然還是希望能對IO進行深度學習,如今可以嘗試使用transferTo()來進行文件的上傳操作,transferTo()源碼底層還是io流來操作
前端頁面寫法(form表單提交):
<form id="formfile" action="slideshowin" method="post" enctype="multipart/form-data">
<label class="col-sm-2 control-label no-padding-right" for="form-field-1">視頻:</label>
<div class="col-sm-3">
<input type="file" id="media" name="myfile" />
<input type="hidden" name="mediaName" value=""/>
</div>
<input type="button" class="btn btn-small btn-base" title="保存" onclick="tijiao();" value="保存">
</form>
js提交爲jq的ajax提交form表單
獲取表單,必須加[0]才能取到數據
var formData =new FormData($("#formfile")[0]);
$.ajax({
url: url,
type: "POST",
data: formData,
cache:false,
contentType: false,
processData: false,
success: function (dat) {
},
error: function (dat) {
}
});
mvc xml文件配置
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="209715200"/>
<property name="defaultEncoding" value="UTF-8"/>
<property name="resolveLazily" value="true"/>
</bean>
後臺代碼提交
public void fileUpload(@RequestParam("myfile") MultipartFile[] myfile) {
try {
int len = myfile.length;
for (int i = 0; i < len; i++) {
MultipartFile file = myfile[i];
if (file.isEmpty()) {
// TODO文件爲空時處理
return;
} else {
file.transferTo(new File("服務器文件上傳目錄" + file.getName()));
//入庫業務
Slideshow slideshow=new Slideshow();
slideshow.setSlideshowImg(file.getOriginalFilename());//文件名
slideshow.setSlideshowState(0);
slideshow.setSlideshowTime(new DataTime().getDatatime());
slideshowService.insert(slideshow);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return;
}
參考文章地址:https://blog.csdn.net/cainiaobulan/article/details/78870934