以文件流的方式 文件上传 下载

HTML:

                                <div class="box-body">
                                    <form id="upload_form" enctype="multipart/form-data"  action="/wjgl/fileSave" method="post">
                                        <!-- 上传用户编号 -->
                                        <input type="hidden" name="userMark" value="${staff.userMark}"/>
                                        <!-- 借款编号 -->        
                                        <input type="hidden" name="qujkId" value="${qyjk.id}"/>
                                        <input type="hidden" name="tabId" value="9"/>
                                        <table>
                                            <tr>
                                                <td>备注</td>
                                                <td><input type ="text" name="details" id="details"/></td>
                                                <td><input type="file" id="upC" name="fileUp" onclick="fileDetail()" onchange="fileUpLoad()" /></td>
                                            </tr>
                                        </table>        
                                        
                                    </form>
                                    <!-- 图片回显 -->
                                    <div>
                                        <!--  <a class="btn btn-primary" id="fileAdd" onClick="tableCreate('tab',-1)">增加</a>-->
                                        
                                    </div>
                                   <table class="table table-bordered" id="tab">
                                            <tr align="left" >
                                                <th>文件编号</th>
                                                <th  >文件名</th>
                                                <th  >文件类型</th>
                                                <th  >上传时间</th>
                                                <th >备注</th>
                                                <th  >操作</th>
                                            </tr>
                                            
                                            <c:if test="${ empty fkWdglXist}">
                                                <tr align="left">                        
                                                   <td align="center" colspan="6">没有上传任何文件</td>
                                                    </tr>
                                            </c:if>
                                            <c:forEach var="fkWdg" items="${fkWdglXist}">  
                                                    <tr align="left">    
                                                       <td>${fkWdg.wjId }</td>                
                                                       <td>${fkWdg.clMc}</td>
                                                       <td>${fkWdg.clFl }</td>
                                                       <td>${fkWdg.scRq }</td>
                                                       <td>${fkWdg.detail}</td>
                                                       
                                                       <td>                                                            
                                                            <a href="/wjgl/downLoad?fileId=${ fkWdg.wjId} "  class="btn btn-primary"  id="down" margin-left:10px>下载</a>
                                                            <a class="btn btn-primary" id="fileDel" name="trDe" onClick="delTr(${fkWdg.wjId})">删除</a>
                                                       </td>
                                                    </tr>
                                            
                                            </c:forEach>
                                        </table>
                             </div>

JAVA:

package net.zkbc.scd.mgt.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.zkbc.scd.mgt.entity.FkWdckX;
import net.zkbc.scd.mgt.entity.FkWdglX;
import net.zkbc.scd.mgt.service.FkWdckxService;
import net.zkbc.scd.mgt.service.FkWdglxService;
import net.zkbc.scd.security.entity.User;
import net.zkbc.scd.security.service.UserService;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


/**
 * 文档管理
 * @author Lizuoqi
 */
@Controller
@RequestMapping(value = "/wjgl")
public class FileManagerController {
    
    //文档
    @Autowired
    private FkWdckxService fkWdckxService;
    
    //文档
    @Autowired
    private FkWdglxService fkWdglxService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 上传文件
     * */
    @ResponseBody
    @RequestMapping(value ="/fileSave",method = RequestMethod.POST)
    public String fileSave(@RequestParam MultipartFile fileUp,String userMark,Long qujkId,HttpServletRequest request,HttpSession session){
        //文档表
        FkWdckX fkWdckx = new FkWdckX();
        //文档管理表
        FkWdglX fkWdglX = new FkWdglX();
        
        //转换为file类型
        CommonsMultipartFile cf= (CommonsMultipartFile)fileUp;
        DiskFileItem fi = (DiskFileItem)cf.getFileItem();
        File f = fi.getStoreLocation();
        
        
        

         
           String filename = fileUp.getOriginalFilename();
           InputStream inputStream;
        try {
            
            //设置上传时间取毫秒
               SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmssSSS");
            try {
                Date time = sdf.parse(sdf.format(new Date()));
                fkWdglX.setScRq(time);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            
            inputStream = fi.getInputStream();
            byte[] b = new byte[1048576];
            int length = inputStream.read(b);
            
            String path = "E:\upload";
            path += "\" + filename;
            // 文件流写到服务器端
            FileOutputStream outputStream = new FileOutputStream(path);
            outputStream.write(b, 0, length);
            //关闭文档写入留
            inputStream.close();
            outputStream.close();
            
            //设置文件url
            fkWdckx.setUrl(path);
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //设置文件名称
        fkWdckx.setFileName(filename);
        //保存上传文件
        fkWdckxService.save(fkWdckx);
        
        //查询到文档相关信息
        FkWdckX fkwd = fkWdckxService.findByFileName(filename);
        
        //保存文档管理
        fkWdglX.setWjId(fkwd.getId());//文件id
        fkWdglX.setJkBh(qujkId);      //借款id
        
        //获取当前登录用户的名字
        String username=(String) SecurityUtils.getSubject().getPrincipal();
        User user = userService.findByLoginName(username);
        
        //设置上传用户id
        fkWdglX.setScyhBh(user.getUserMark());
        
        //保存文档管理表
        fkWdglxService.save(fkWdglX);
        
        
        return "2";
    }
    
    /**
     * 下载文件
     * */
    @ResponseBody
    @RequestMapping(value ="/downLoad")
    public String downLoad(String fileName, HttpServletResponse response){
            String path = "E:\upload\new  1.txt";
           try {
                // path是指欲下载的文件的路径。
                File file = new File(path);
                // 取得文件名。
                String filename = file.getName();
                // 取得文件的后缀名。
                String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(path));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        return "";
    }

}

原文地址:https://www.cnblogs.com/lizuoqi/p/4210048.html