java實現文件上傳首先必須將form表單的enctype屬性設置成multipart/form-data,才能進行提交java
<form id="form-test" method="post" class="validate" enctype="multipart/form-data">web
</form>ajax
有了表單就要有文件選擇控件apache
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">選擇文件</label>
<input type="file" class="file" name="myFile" />
</div>
</div>tomcat
而後就能夠將選擇的文件提交到服務器的方法了服務器
$('#form-test').ajaxForm({
url: 'postFile/create',
success: function(response) {
if (!response.success) {
errorHandler(response);
return;
}
}
});app
$('#form-test').ajaxForm({
url: 'postFile/remove',
data: function ( d ) {
d.url = "D:\apache-tomcat-6.0.43\webapps\file"
}
success: function(response) {
if (!response.success) {
errorHandler(response);
return;
}
}
});webapp
服務器中的方法就是這樣post
//上傳
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public Boolean create(MultipartFile myFile, HttpServletRequest request) throws IOException {
try{
String realPath = request.getSession().getServletContext().getRealPath("file/softpackage");//指定tomcat下的相對路徑
FileUtils.copyInputStreamToFile(myFile.getInputStream(), new File(realPath, myFile.getOriginalFilename()));
//myFile.getOriginalFilename()獲取上傳的文件名稱
//將文件從本地路徑複製到服務器路徑url
return true;
}catch(Exception e){
return false;
}
}
//刪除
@RequestMapping("/remove/{url}")
@ResponseBody
public Boolean remove(@PathVariable String url) {
File file = new File(url);
if (file.exists()) {
file.delete();
return true;
}
return false;
}