经测试能用springmvc的文件上传下载并解决ie8文件上传后提示下载

这两天领导让写一个文件上传下载的功能,由于是新手,忙了一天查资料,终于搞定了,经过测试了,给各位看一下,共同学习

一、先写测试好的上传功能

首先是实体类

@Data
public class FileUpload {
    private byte[] bytes; //输入字节流
    private String fileName; //文件名字
    private String fileuuid;
}

然后是controller

前台jsp页面input的name必须与参数名相同,multipartFile

如果是多文件上传,参数定义为MultipartFile[] multipartFile就可以,然后里面遍历处理

@RequestMapping("/uploadFile")
    @ResponseBody
    public ExecuteResult<FileUpload> uploadFile(HttpServletRequest request, MultipartFile multipartFile) {
        ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>();//自己定义的结果集
        FileUpload fileUpload = new FileUpload();//自己定义的实体类
        try {
            fileUpload.setFileName(multipartFile.getOriginalFilename());//获得文件名字,类如:  周报.xls
            InputStream is = multipartFile.getInputStream();//从multipartFile中获得输入流
            fileUpload.setBytes(IOUtils.toByteArray(is));//从输入流中获得字节流
            IOUtils.closeQuietly(is);//关闭输入流
            execute = fileUploadService.uploadFile(fileUpload);//调用service方法存放文件
            response.setContentType("text/json;charset=UTF-8"); //解决ie8上传后提示下载的问题
        } catch (IOException e) {
            LOGGER.error("e", e);
            execute.addErrorMessage(LOGGER.toString());
        } catch (Exception e) {
            LOGGER.error("e", e);
            execute.addErrorMessage(LOGGER.toString());
        }
        return execute;
    }

然后是service

public ExecuteResult<FileUpload> uploadFile(FileUpload fileUpload) {
        ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>();
        fileUpload.setFileuuid(UUID.randomUUID().toString());//生成uuid
        String uploadPath = Env.getProperty(Env.FILE_UPLOAD_URL);//此处是项目中自己配置的上传路径"d:/"
        String filePath = uploadPath + fileUpload.getFileuuid();//路径加UUID
        File file = new File(filePath);//此文件会存放在指定文件夹下,文件名字为UUID,并且没有后缀名
        try {
            if (!new File(filePath).exists()) {//判断此文件是否存在了,因为是UUID名字,所以一般不会重复
                FileUtils.writeByteArrayToFile(file, fileUpload.getBytes());//调用FileUtils的方法,将文件写到指定位置,第一个参数为file,第二个参数为输入字节流
           }else {
         fileUpload.setFileuuid(UUID.randomUUID().toString());
         FileUtils.writeByteArrayToFile(new File(uploadPath + fileUpload.getFileuuid()), fileUpload.getBytes());
      }
         fileUploadMapper.uploadFile(fileUpload);
         execute.setResult(fileUpload);
       } catch (IOException e) {
         LOGGER.error("e", e);
         execute.addErrorMessage(LOGGER.toString());
       } catch (Exception e) {
         LOGGER.error("e", e);
         execute.addErrorMessage(LOGGER.toString());
       }
     return execute;
    }

二、刚才经过测试,下载的也实现了,并解决ie8下载时文件名字乱码问题,代码如下

controller层:

 @RequestMapping("/downloadFile")
    @ResponseBody
    public void fileDownLoad(HttpServletRequest request, HttpServletResponse response, String fileuuid) {
        //String fileuuid = request.getParameter("fileuuid");
        ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>();
        ServletContext application = request.getSession().getServletContext();
        try {
            execute = fileUploadService.dowloadFile(fileuuid);
            byte[] bytes = execute.getResult().getBytes();
            response.reset();
            String fileName = execute.getResult().getFileName();
            String userAgent = request.getHeader("User-Agent");
            //针对IE或者以IE为内核的浏览器:
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
            //非IE浏览器的处理:
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            //response.addHeader("Content-Disposition", "attachment;filename=" + new String(execute.getResult().getFileName().replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));
            //response.addHeader("Content-Length", "" + bytes.length); //此处需要验证是否正确
            //设置文件MIME类型
            response.setContentType(application.getMimeType(fileName));
            response.setCharacterEncoding("UTF-8");
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            LOGGER.error("e", e);
        } catch (Exception e) {
            LOGGER.error("e", e);
        }
    }

相应前台

<input type="file" name="multipartFile" id="fileUpload" class="colorblur" οnblur="this.className='colorblur';" οnfοcus="this.className='colorfocus';">
<input type="submit" name="btnUpload" value="上传" id="btnUpload" class="btn">



  
  1.  $('#fileToUpload').on('change', function() {  
  2.         $.ajaxFileUpload({  
  3.             url:'../FileUploadServlet',  
  4.             secureuri:false,  
  5.             fileElementId:'fileToUpload',//file标签的id  
  6.             dataType: 'json',//返回数据的类型  
  7.             data:{fileuuid:'3242354'},//一同上传的数据  
  8.             success: function (data) {  
  9.                
  10.             },  
  11.             error:{ 
  12.             }  
  13.         });  
  14.     }); 

最后把mapper也放出来吧,省的你们觉得代码不全看不懂。。


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="项目.dao.FileUploadMapper">
 
	<resultMap id="fileResultMap" type="。。。。。。。。.FileUpload">
		<result property="fileName" column="FILE_NAME" />
		<result property="fileuuid" column="FILEUUID" />
	</resultMap>

	<insert id="uploadFile" parameterType="。。。。。。。。.FileUpload" >
		INSERT INTO 表名 (FILE_NAME,FILEUUID)
		VALUES (#{fileName},#{fileuuid})
	</insert>

	<select id="getFileUpload" resultMap="fileResultMap">
		SELECT * FROM 表名
		WHERE FILEUUID = #{fileuuid}
	</select>
</mapper>

另一种写法 




import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/file")
public class FileUploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);

    @Resource
    private FileUploadService fileUploadService;

    /**
     *
     * @param request
     * @param multipartFile
     * @return
     */
    @RequestMapping("/uploadFile")

    public ExecuteResult<FileUpload> uploadFile(HttpServletRequest request, MultipartFile multipartFile, String createBy, String document, String createUserName, HttpServletResponse response) {
        ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>();
        InputStream is = null;
        FileUpload fileUpload = new FileUpload();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if (multipartFile == null) {
                execute.addErrorMessage("上传文件为空");
                response = checkPro(response, execute);
                return null;
            }
            if (StringUtils.isBlank(createBy) || StringUtils.isBlank(createUserName)) {
                execute.addErrorMessage("创建人或单据号为空");
                response = checkPro(response, execute);
                return null;
            }

            fileUpload.setFileName(multipartFile.getOriginalFilename());
            fileUpload.setCreateBy(createBy);
            fileUpload.setDocument(document);
            fileUpload.setCreateUserName(createUserName);
            fileUpload.setCreateDate(df.format(new Date()));
            is = multipartFile.getInputStream(); //获得输入流
            fileUpload.setBytes(IOUtils.toByteArray(is));
            IOUtils.closeQuietly(is); //关闭输入流
            execute = fileUploadService.uploadFile(fileUpload);
            response = checkPro(response, execute);
            response.getWriter().flush();
        } catch (IOException e) {
            LOGGER.error("e", e);
            execute.addErrorMessage(e.getMessage());
        } catch (Exception e) {
            LOGGER.error("e", e);
            execute.addErrorMessage(e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException  e) {
                    LOGGER.error("e", e);
                    execute.addErrorMessage(e.getMessage());
                }
            }
        }
        return null;
    }

    /**
     *
     * @param request
     * @param response
     */
    @RequestMapping("/downloadFile")
    public void fileDownLoad(HttpServletRequest request, HttpServletResponse response, String fileuuid) {
        ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>();
        ServletContext application = request.getSession().getServletContext();
        OutputStream os = null;
        try {
            execute = fileUploadService.dowloadFile(fileuuid);
            byte[] bytes = execute.getResult().getBytes();
            response.reset();
            String fileName = execute.getResult().getFileName();
            String userAgent = request.getHeader("User-Agent");
            //针对IE或者以IE为内核的浏览器:
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = java.net.URLEncoder.encode(fileName, "gb2312");
            } else {
            //非IE浏览器的处理:
                fileName = new String(fileName.getBytes("gb2312"), "ISO-8859-1");
            }
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            //response.addHeader("Content-Disposition", "attachment;filename=" + new String(execute.getResult().getFileName().replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));
            //response.addHeader("Content-Length", "" + bytes.length); //此处需要验证是否正确
            //设置文件MIME类型
            response.setContentType(application.getMimeType(fileName));
            response.setCharacterEncoding("gb2312");
            os = new BufferedOutputStream(response.getOutputStream());
            os.write(bytes);
            os.flush();
        } catch (IOException e) {
            LOGGER.error("e", e);
        } catch (Exception e) {
            LOGGER.error("e", e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error("e", e);
                    execute.addErrorMessage(e.getMessage());
                }
            }
        }
    }
    @RequestMapping("/deleteFile")
    @ResponseBody
    public ExecuteResult<FileUpload> deleteFile(@RequestBody DocumentList documentList) {
        ExecuteResult<FileUpload> executeResult = new ExecuteResult<FileUpload>();

        List<String> documents = documentList.getDocuments();
        if (documents.isEmpty() || null == documents.get(0)) {
            executeResult.addErrorMessage("请至少选择一条单据");
            return executeResult;
        }

        return fileUploadService.deleteFile(documents);
    }

    @RequestMapping("/getFilesByDocument")
    @ResponseBody
    public List<FileUpload> getFilesByDocument(String document) {
        return fileUploadService.getFilesByDocument(document);
    }
    /*
        判断项目是否和.net跨域并处理response
     */
    public HttpServletResponse checkPro(HttpServletResponse response, ExecuteResult<FileUpload> execute) throws IOException {
        if (APPNAME.OPPLERS.getAppName().equals(Env.getProperty(Env.KEY_SERVER_NAME))) {
            response.setContentType("text/html; charset=GB2312"); //解决ie8上传后提示下载的问题
            response.getWriter().write(JSONObject.fromObject(execute).toString() + "<script>document.domain='opple.com'</script>");
        } else {
            response.setContentType("text/html; charset=UTF-8"); //解决ie8上传后提示下载的问题
            response.getWriter().write(JSONObject.fromObject(execute).toString());
        }
        return response;
    }
}

service

public class FileUploadServiceImpl implements FileUploadService {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadServiceImpl.class);

    @Getter@Setter
    private FileUploadMapper fileUploadMapper;

    /**
     * 文件上传
     * @param fileUpload 上传文件
     * @return ExecuteResult<FileUpload>
     */
    @Override
    public ExecuteResult<FileUpload> uploadFile(FileUpload fileUpload) {
        ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>();
        fileUpload.setFileuuid(UUID.randomUUID().toString());
        String uploadPath = Env.getProperty(Env.FILE_UPLOAD_URL);
        String filePath = uploadPath + fileUpload.getFileuuid();
        File file = new File(filePath);
        try {
            if (!new File(filePath).exists()) {
                FileUtils.writeByteArrayToFile(file, fileUpload.getBytes());
            } else {
                fileUpload.setFileuuid(UUID.randomUUID().toString());
                FileUtils.writeByteArrayToFile(new File(uploadPath + fileUpload.getFileuuid()), fileUpload.getBytes());
            }
            fileUploadMapper.uploadFile(fileUpload);
            fileUpload.setBytes(null);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            fileUpload.setCreateDate(sdf.format(new Date()));
            execute.setResult(fileUpload);
        } catch (IOException e) {
            LOGGER.error("e", e);
            execute.addErrorMessage(LOGGER.toString());
        } catch (Exception e) {
            LOGGER.error("e", e);
            execute.addErrorMessage(LOGGER.toString());
        }
        return execute;
    }

    /**
     * 文件下载
     * @param fileuuid uuid
     * @return ExecuteResult<FileUpload>
     */
    @Override
    public ExecuteResult<FileUpload> dowloadFile(String fileuuid) {
        ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>();
        InputStream fis = null;
        try {
            FileUpload fileUpload = fileUploadMapper.getFileUpload(fileuuid);
            String uploadPath = Env.getProperty(Env.FILE_UPLOAD_URL);
            String filePath = uploadPath + fileUpload.getFileuuid();
            fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = IOUtils.toByteArray(fis);
            fileUpload.setBytes(buffer);
            execute.setResult(fileUpload);
            fis.close();
        } catch (IOException e) {
            LOGGER.error("e", e);
            execute.addErrorMessage(LOGGER.toString());
        } catch (Exception e) {
            LOGGER.error("e", e);
            execute.addErrorMessage(LOGGER.toString());
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    LOGGER.error("e", e);
                    execute.addErrorMessage(LOGGER.toString());
                }
            }
        }
        return execute;
    }

    @Override
    public ExecuteResult<FileUpload> deleteFile(List<String> list) {
        ExecuteResult<FileUpload> execute = new ExecuteResult<FileUpload>();
        String fileuuid = null;
        String uploadPath = null;
        String sPath = null;
        File file = null;
        boolean flag = false;
        try {
            // 判断目录或文件是否存在
            for (int i = 0; i< list.size(); i++) {

                fileuuid = list.get(i);
                uploadPath = Env.getProperty(Env.FILE_UPLOAD_URL);
                sPath = uploadPath + fileuuid;
                file = new File(sPath);
                if (file.exists())  {
                    // 判断是否为文件
                    if (file.isFile()) {  // 为文件时调用删除文件方法
                        flag = deleteFileUtil(sPath);
                        if (flag) {
                            fileUploadMapper.deleteFile(fileuuid);
                        }
                    }
                }
             }
        } catch (Exception e) {
            LOGGER.error("e", e);
            execute.addErrorMessage(e.getMessage());
        }
        return execute;
    }

    @Override
    public List<FileUpload> getFilesByDocument(String document) {
        return fileUploadMapper.getFilesByDocument(document);
    }

    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public boolean deleteFileUtil(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
}

  • 3
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 2
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论 2

打赏作者

不急god

感谢您的打赏

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值