标签:
java实现文件上传首先必须将form表单的enctype属性设置成multipart/form-data,才能进行提交
<form id="form-test" method="post" class="validate" enctype="multipart/form-data">
</form>
有了表单就要有文件选择控件
<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>
然后就可以将选择的文件提交到服务器的方法了
$(‘#form-test‘).ajaxForm({
url: ‘postFile/create‘,
success: function(response) {
if (!response.success) {
errorHandler(response);
return;
}
}
});
$(‘#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;
}
}
});
服务器中的方法就是这样
//上传
@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()获取上传的文件名称
//将文件从本地路径复制到服务器路径
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;
}
标签:
原文地址:http://www.cnblogs.com/zhang-xiao-fan/p/4435389.html