java代码实现文件上传、下载、删除处理。

平时工作中经常遇到文件上传、下载、删除等处理,所以专门做一下记录,以便日后需要。

1、文件上传。

  1. 配置。
    首先定义文件上传到服务器后,在服务器上的存放路径。(application.properties)
    #文件上传目录
    file.upload.url= E:/test
  2. 逻辑层实现。
    上传文件比较简单,我们就直接在controller层来编写。也不用在pom.xml 中增加什么依赖。所以直接上代码。在controller 包下创建一个FileController 类。代码如下:
    	@RestController
    	@RequestMapping("file")
    	@Slf4j
    	public class FileController {
    	    @Value("${file.upload.url}")
    	    private String uploadFilePath;
    	
    	        @RequestMapping("/upload")
    	    	public String httpUpload(@RequestParam("files") MultipartFile files[]){
    	        JSONObject object=new JSONObject();
    	        for(int i=0;i<files.length;i++){
    	            String fileName = files[i].getOriginalFilename();  // 文件名
    	            File dest = new File(uploadFilePath +'/'+ fileName);
    	            if (!dest.getParentFile().exists()) {
    	                dest.getParentFile().mkdirs();
    	            }
    	            try {
    	                files[i].transferTo(dest);
    	            } catch (Exception e) {
    	                log.error("{}",e);
    	                object.put("success",2);
    	                object.put("result","程序错误,请重新上传");
    	                return object.toString();
    	            }
    	        }
    	        object.put("success",1);
    	        object.put("result","文件上传成功");
    	        return object.toString();
    	    }
    
    上面的代码看起来有点多,其实就是一个上传的方法,首先通过 MultipartFile 接收文件。这里我用的是file[] 数组接收文件,这是为了兼容多文件上传的情况,如果只用file 接收,然后在接口上传多个文件的话,只会接收最后一个文件。
 File dest = new File(uploadFilePath +'/'+ fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

这里大家注意一下。看自己的需求,我这里兼容多文件所以用数组接收。然后遍历files 获取文件,下面这段代码是判断文件在所在目录是否存在,如果不存在就创建对应的目录。

	files[i].transferTo(dest);

就是将文件存放到对应的服务器,这里有一点需要说明一下,如果我们上传重复的文件会怎么样么?上传重复的文件不会报错,后上传的文件会直接覆盖已经上传的文件。
整体代码就是这样。现在就可以实现文件的上传操作。

2.文件下载。

其实文件下载,不太建议用接口做,因为文件下载一般都是下载一些静态文件,我们可以先将文件处理好,然后通过Nginx 服务下载静态文件,这样速度会快很多。但是这里我们还是写一下。代码也很简单,就一个方法,也写在fileController 类中,代码如下:

 @RequestMapping("/download")
    public String fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName){
        File file = new File(downloadFilePath +'/'+ fileName);
        if(!file.exists()){
            return "下载文件不存在";
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName );

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            log.error("{}",e);
            return "下载失败";
        }
        return "下载成功";
    }
代码也很简单,就是根据文件名判断是否存在文件,不存在就提示没有文件,存在就将文件下载下来。response设置返回文件的格式,以文件流的方式返回,采用utf-8 字符集,设置下载后的文件名。然后就是以文件流的方式下载文件了。如果文件存在,会直接下载,不会提示下载成功或者失败。

3.文件删除。

删除文件是很简单的,我这里讲一下删除文件下所有文件夹和文件。并做一个定时任务,每天清理一次。有其他需求可以按需要截取代码。如下:

    @Scheduled(cron="0 0 3 * * ?")
    private void deleteFiles(){
        deleteFile(new File(deleteFilePath));
    }

    public void deleteFile(File file){
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()){
            log.info("暂无文件");
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files){
            //打印文件名
            String name = f.getName();
            log.info(name);
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()){
                deleteFile(f);
            }else {
                f.delete();
            }
        }
        //删除空文件夹  for循环已经把上一层节点的目录清空。
        file.delete();
    }
    ```


  • 18
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的文件上传下载Java 代码示例,使用了工作流(Workflow)实现文件上传: ```java import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.TransferManagerBuilder; import com.amazonaws.services.s3.transfer.Upload; public class FileUpload { public static void main(String[] args) throws Exception { // 1. 读取配置文件 Properties props = new Properties(); InputStream in = new FileInputStream("config.properties"); props.load(in); // 2. 创建 Amazon S3 客户端 String accessKey = props.getProperty("accessKey"); String secretKey = props.getProperty("secretKey"); String region = props.getProperty("region"); BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey); AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .withRegion(region) .build(); // 3. 创建 TransferManager TransferManager transferManager = TransferManagerBuilder.standard() .withS3Client(s3Client) .build(); // 4. 从 HTTP 请求中获取文件 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); FileItem item = upload.parseRequest(request).get(0); String fileName = item.getName(); // 5. 上传文件到 Amazon S3 PutObjectRequest putRequest = new PutObjectRequest( props.getProperty("bucketName"), fileName, item.getInputStream(), new ObjectMetadata()); Upload upload = transferManager.upload(putRequest); upload.waitForCompletion(); // 6. 删除临时文件 FileUtils.deleteQuietly(new File(item.getName())); } } ``` 文件下载: ```java import java.io.File; import java.io.FileOutputStream; import java.util.Properties; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.TransferManagerBuilder; import com.amazonaws.services.s3.transfer.Download; public class FileDownload { public static void main(String[] args) throws Exception { // 1. 读取配置文件 Properties props = new Properties(); InputStream in = new FileInputStream("config.properties"); props.load(in); // 2. 创建 Amazon S3 客户端 String accessKey = props.getProperty("accessKey"); String secretKey = props.getProperty("secretKey"); String region = props.getProperty("region"); BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey); AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) .withRegion(region) .build(); // 3. 创建 TransferManager TransferManager transferManager = TransferManagerBuilder.standard() .withS3Client(s3Client) .build(); // 4. 从 Amazon S3 下载文件 S3Object object = s3Client.getObject(props.getProperty("bucketName"), props.getProperty("fileName")); Download download = transferManager.download( props.getProperty("bucketName"), props.getProperty("fileName"), new File(props.getProperty("localPath"))); download.waitForCompletion(); // 5. 关闭 Amazon S3 客户端和 TransferManager object.close(); transferManager.shutdownNow(); } } ``` 以上代码示例使用了 Amazon S3 作为文件存储和下载服务,需要提供以下配置信息: - `accessKey`: AWS 访问密钥 ID - `secretKey`: AWS 秘密访问密钥 - `region`: AWS 区域 - `bucketName`: 存储桶名称 - `fileName`: 文件名称 - `localPath`: 下载到本地的路径

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值