文件上传与下载,springMVC


动态图标可设置

文件上传与下载

package com.abview.action;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@ResponseBody
@RequestMapping("/static")
@SuppressWarnings("unchecked")
public class FileAction {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    FileServer fileServer;

    @PostMapping("/modelImg/upload")
    public String upload(@RequestParam("pimage") MultipartFile file, HttpServletRequest req){
        logger.info("文件上传...");
        if (file.isEmpty()){
            return "上传文件不能为空";
        }
        String filePath = null;
        try {
            filePath = fileServer.upload(file,req);
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }
        JSONObject respJson = new JSONObject();
        respJson.put("imgurl",filePath);
        return JSONUtil.toJsonStr(respJson);
    }
//    @PostMapping("/upload")
//    public String file_upload(@RequestParam("pimage") MultipartFile file, HttpServletRequest req) {
//        logger.info("文件上传...");
//        if (file.isEmpty()){
//            return "上传文件不能为空";
//        }
//        String filePath = null;
//        try {
//            filePath = fileServer.upload(file,req);
//        } catch (IOException e) {
//            e.printStackTrace();
//            return "文件上传失败";
//        }
//        //回显图片  返回客户端JSON对象,封装图片的路径,为了在页面实现立即回显
//        JSONObject object = new JSONObject();
//        object.put("imgurl", filePath);//imgurl保存图片名称{"imgurl":"http://localhost:80/images/modelImg/2f94770d77324883a64cd0b67afa3537.png"}
//        return object.toString();
//    }

    @GetMapping("/modelImg/{fileName}")
    public void download(HttpServletRequest req, HttpServletResponse res,@PathVariable String fileName){
        logger.info("文件下载....无效参数->文件名:{}",fileName);
        try {
            fileServer.download(req, res);
        } catch (IOException e) {
            logger.info("文件下载异常");
            e.printStackTrace();
        }
    }

}

上传下载服务

package com.abview.action;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.abview.common.pojo.ABResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: demo
 * @ClassName FileUtils
 * @author: hrf
 * @create: 2022-11-18 13:44
 * @description: TODO
 * @Version 1.0
 **/
//不写这个怎么注册为bean
@Component
public class FileServer {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Value("${lauFile.root}")
    private String root;
    @Value("${lauFile.protocol}")
    private String protocol;

    private String basePath = "/ra/static/modelImg/";

    //下载图片解析的文件后缀集合
    static List<String> imgSuffix;
    static {
        imgSuffix  = new ArrayList<>();
        imgSuffix.add("png");
        imgSuffix.add("jpg");
        imgSuffix.add("jpeg");
        imgSuffix.add("gif");
        imgSuffix.add("svg");
    }

    /**
     * 默认创建临时目录 不考虑盘符默认第一个盘
     * @param path 子目录
     * @return 标识
     */
    public String mkDir(String path) throws IOException {
        return this.mkDir(null,path);
    }
    /**
     * 指定盘符创建目录
     * @param parent 盘符-不区分大小写
     * @param child 目录
     * @return 标识
     */
    public String mkDir(String parent,String child) throws IOException {
        File temporaryFile = new File(getRoot(parent),child);
        logger.info("DIRECTORY PATH:{}",temporaryFile);
        //如果不存在目录则创建目录
        if (!temporaryFile.exists()){
            temporaryFile.mkdirs();
        }
        return temporaryFile.getPath();
    }
    public File getRoot(String parent) throws IOException {
        File[] roots = File.listRoots();
        if (StringUtils.isBlank(parent)) {
            return roots[0];
        }
        //目的盘符
        String purposePath = parent.substring(0, 1).toUpperCase();
        //检查是否存在目的盘符
        List<File> path = Arrays.stream(roots).filter(item -> {
            String rootPath = item.getPath().toUpperCase().substring(0,1);
            if (rootPath.equals(purposePath)) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        if (path.size() == 0){
            logger.info("创建目录目的盘符不存在");
            throw new IOException("盘符不存在");
        }
        return path.get(0);
    }
    public String upload(MultipartFile file,HttpServletRequest req) throws IOException {
        logger.info("文件上传中.......");
        String oldName = file.getOriginalFilename();
        String path;
        if (StringUtils.isNotBlank(root)){
            path = mkDir(root,basePath);
        }else {
            path = mkDir(basePath);
        }
        String newName = IdUtil.fastSimpleUUID()
                + oldName.substring(oldName.lastIndexOf("."));
        file.transferTo(new File(path,newName));
        return protocol + "://" + req.getServerName() + ":" + req.getServerPort() + basePath + newName;
    }
    public void download(HttpServletRequest req, HttpServletResponse res) throws IOException {
        String path = URLDecoder.decode(req.getRequestURI());
        logger.info("文件下载中.....path:{}",path);
        String filePath;
        if (StringUtils.isNotBlank(root)){
            filePath = mkDir(root,path);
        }else {
            filePath = mkDir(path);
        }
        File file = new File(filePath);
        if (!file.exists()){
            throw new IOException("文件不存在");
        }
        if (!file.isFile()){
            throw new IOException("文件异常");
        }
        long length = file.length();

        String fileName = file.getName();
        String fileSuffix = fileName.split("\\.")[1];
        res.addHeader("Content-Length",String.valueOf(length));
        if (!imgSuffix.contains(fileSuffix)){
            //放开下面的注释文件会下载下来
            res.setHeader("Content-Disposition", "attachment;filename="+fileName);
        }else {
            res.addHeader("Content-Type","image/jpeg");
        }

        OutputStream outputStream = res.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        FileInputStream inputStream = new FileInputStream(file);
        bis = new BufferedInputStream(inputStream);
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        bis.close();
        outputStream.close();
    }

    /**
     *
     * @param req
     * @param fileUrl
     * @param modelSerial
     * @return
     * @throws IOException
     */
    public ABResponse reFileName(HttpServletRequest req, String fileUrl, String modelSerial) throws IOException {

        logger.info("[{}] will reName to [{}]",fileUrl,modelSerial);
        String path = fileUrl.substring(fileUrl.lastIndexOf(basePath));
        String filePath = getRoot(root).getPath().replace("\\","") + path;

        File file = new File(filePath);
        String oldFileName =  file.getName();

        modelSerial = modelSerial + "." + oldFileName.split("\\.")[1];
        String newFilePath = filePath.replace(oldFileName, modelSerial);
        boolean rename = file.renameTo(new File(newFilePath));
        if (rename) {
            String pathUrl = protocol +"://"+ req.getServerName()+":"+req.getServerPort()+ newFilePath.split(":")[1];
            JSONObject respJson = new JSONObject();
            respJson.set("newFileUrl",pathUrl.replaceAll("\\\\","/"));
            return ABResponse.buildSuccessData(respJson);
        }
        return ABResponse.buildFail();
    }

    public ABResponse deleteFile(JSONObject fileInfo) throws IOException {
        String fileUrl = fileInfo.getStr( "fileUrl");
        String path = fileUrl.substring(fileUrl.lastIndexOf(basePath));
        String filePath = getRoot(root).getPath() .replace("\\","")+ path;
        logger.info("原url:{}",filePath);
        File file = new File(filePath);
        file.deleteOnExit();
        return ABResponse.buildSuccess();
    }
    public ABResponse deleteFileUrl(String fileUrl) throws IOException {
        String path = fileUrl.substring(fileUrl.lastIndexOf(basePath));
        String filePath = getRoot(root).getPath()
                .replace("\\","" )+ path .replace( "/", "\\");
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        return ABResponse.buildSuccess();
    }
}

在springmvc.xml中@value的使用

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
	xsi:schemaLocation="http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-2.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

<!--	扫面组件-->
	<context:component-scan base-package="com.abview.action" />
	
	<!-- 注解定时任务 -->
	<task:annotation-driven />

	<!-- 加上这个,aop才能生效 -->
	<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
	<aop:aspectj-autoproxy expose-proxy="true"></aop:aspectj-autoproxy>



	<mvc:default-servlet-handler />
	<!-- 资源映射 -->
	<mvc:resources location="/WEB-INF/css/" mapping="/css/**" />
	<mvc:resources location="/WEB-INF/images/" mapping="/images/**" />
	<mvc:resources location="/WEB-INF/js/" mapping="/js/**" />
	<mvc:resources location="/WEB-INF/lib/" mapping="/lib/**" />
	<mvc:resources location="/WEB-INF/html/" mapping="/html/**" />
	<mvc:resources location="/WEB-INF/upload/" mapping="/upload/**" />

	<mvc:resources location="/WEB-INF/fonts/" mapping="/fonts/**" />

	<mvc:annotation-driven>
		<mvc:message-converters>
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<property name="supportedMediaTypes">
					<list>
						<value>text/plain;charset=UTF-8</value>
						<value>text/html;charset=UTF-8</value>
					</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/html/" />
		<property name="suffix" value=".html" />
	</bean>


	<!-- 定义文件上传解析器 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设定默认编码 -->
		<property name="defaultEncoding" value="UTF-8"></property>
		<!-- 设定文件上传的最大值1G,1024*1024*1024 -->
		<property name="maxUploadSize" value="1073741824"></property>
	</bean>
	
	<context:component-scan base-package="com.abview.websocket"></context:component-scan>

	<!-- @Value -->
	<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
		<property name="locations">
			<list>
				<value>classpath*:files.properties</value>
			</list>
		</property>
	</bean>
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
		<property name="properties" ref="configProperties" />
	</bean>
</beans>

files.properties

lauFile.root = F
lauFile.protocol = http

工具类

package com.abview.utils;
import java.util.UUID;

public class FileNameUtil {
	//根据UUID生成文件名
	public static String getUUIDFileName() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replace("-", "");
	}
	//从请求头中提取文件名和类型
	public static String getRealFileName(String context) {
		// Content-Disposition: form-data; name="myfile"; filename="a_left.jpg"
		int index = context.lastIndexOf("=");
		String filename = context.substring(index + 2, context.length() - 1);
		return filename;
	}
	//根据给定的文件名和后缀截取文件名
	public static String getFileType(String fileName){
		//9527s.jpg
		int index = fileName.lastIndexOf(".");
		return fileName.substring(index);
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值