实现文件上传服务器某一路径或者删除服务器某一路径下的文件

/**
* 上传文件
* @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后使用上边的上传和删除功能!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值