* 上传文件
* @return
*/
public String upload(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
InputStream inStream = null;
String savePath = request.getRealPath("/")+"test/upyml/";
File test = new File(savePath);
if(!test.exists()){
test.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String ymd = sdf.format(new Date());
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper)request;
String fileName = wrapper.getFileNames("file")[0];
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
//文件保存目录URL
String saveUrl = savePath +ymd+"."+fileExt;
File test1 = new File(saveUrl);
if(!test1.exists()){
try {
test1.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
int bytesum = 0;
int byteread = 0;
try {
if (file.exists()) {
YmlModel ymlm= new YmlModel();
inStream = new FileInputStream(file);
FileOutputStream fs = new FileOutputStream(saveUrl);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
// System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
ymlm.setYml_file(fileName);
ymlm.setYml_upfile(ymd+"."+fileExt);
ymlm.setYml_time(DateUtil.getDateline());
this.logiManager.addYml(ymlm);
this.showSuccessJson("上传成功!");
}
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
return this.JSON_MESSAGE;
}
/**
* 删除文件
* @return
*/
public String deleyml(){
HttpServletRequest request = this.getRequest();
Integer yml_id = Integer.valueOf(request.getParameter("yml_id"));
YmlModel yml = this.logiManager.queryforYml(yml_id);
String file = null;
if(yml!=null){
file = yml.getYml_upfile();
}
try {
this.logiManager.deleteyml(yml_id);
String savePath = request.getRealPath("/") + "test/upyml/";
if(file!=null && !StringUtils.isEmpty(file)){
File delfile = new File(savePath + file);
if(delfile.exists()){
FileUtil.delete(savePath + file);
}
}
this.showSuccessJson("删除文件成功!");
} catch (Exception e) {
this.showErrorJson("删除失败!");
}
return this.JSON_MESSAGE;
}
/**
* 删除文件或文件夹
*
* @param filePath
*/
public static void delete(String filePath) {
try {
File file = new File(filePath);
if (file.exists()){
if(file.isDirectory()){
FileUtils.deleteDirectory(file);
}else{
file.delete();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
前台页面:
<td><input class="easyui-validatebox input_text" type="file" name="file" isrequired="true"></input></td>
后台获取file后使用上边的上传和删除功能!