js+html+java上传下载文件

<div>
                            <div>
                                <legend class="search_legend" style="font-size: 14px"><strong>附件 </strong></legend>
                                <input ng-model="txtFoo" type="text" id="txtFoo" readonly style="width: 353px;">
                                <input class="btn btn-info" type="button" onclick="file.click()" value="选择文件">
                                <span style="color: red">(支持类型png、jpg、gif、zip、rar,单个文件最大5M,最多10个文件)</span>
                                <input type="file" id="file" multiple="multiple" name="files" style="visibility:hidden">
                            </div>
                            <div class="form-group">
                                <div class="col-sm-8 mgt15">
                                    <div class="col-sm-7">
                                        <table  class="table table-striped" >
                                            <tbody>
                                            <tr ng-repeat="i in addParamsm.qaFileRelationList">
                                                <th>{{i.filename}}</a></th>
                                                <th style="width: 150px">
                                                    <button class='btn btn-primary btn-xs' type='button' ng-click='dowonload(i.id,i.filename)'><i class='fa fa-download'></i>		
                                                    </button> 
                                                    <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                                    <button class='btn btn-danger btn-xs' type='button' ng-click='removePic(i.id)'><i class='fa fa-trash-o'></i></button>
                                                </th>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
$scope.dowonload = function (pid,filename) {
            var fd = new FormData();
            fd.append("id", pid);
            $http({
                method:'POST',
                url  : 'demo/download.do?id=' + pid,
                data: fd,
                responseType: 'blob',
            }).success(function (response) {
                downLoadFile(response,filename)
            }).error(function () {
            });
        };
$scope.removePic = function (pid) {
            $rootScope.ajax.post("demo/removeFileRelation.do?id=" + pid, {})
                .then(function (result) {
                    //$scope.id=result.data;
                    if (result.code == "000000") { //成功
                        alert(result.msg);
                        $scope.getScriptById();
                    } else { //失败
                        alert(result.msg);
                    }
                })
        }
@RequestMapping(value = "/download")
    public JsonResult download(HttpServletRequest request, HttpServletResponse response, Long id) {
       
        FileDTO fileDTO= demoService.dowonloadFileRelation(id);
        String realName = fileDTO.getFilename(); //文件在浏览器的显示位置
        String osName = System.getProperty("os.name");
        String downLoadPath; //这个参数表示文件在服务器的存储路径
        if (osName.toUpperCase().contains("windows".toUpperCase())) {//windows系统下路径
            downLoadPath = "D:\\upload\\2020-07-22\\a.jpg";
        } else {
            downLoadPath = fileDTO.getFilepath();
        }

        String contentType = "application/octet-stream";
        try {
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
            BufferedInputStream bis;
            BufferedOutputStream bos;

            long fileLength = new File(downLoadPath).length();

            response.setContentType(contentType);
            response.setHeader("Content-disposition",
                    "attachment; filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));

            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(MsgCode._error);
        }
    }
@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public JsonResult uploadFiles(@RequestParam(value = "files") MultipartFile[] files, @RequestParam(value = "id") String id, HttpServletRequest request, HttpServletResponse response) {
        Map res = new HashMap();
        JsonResult jsonResult = new JsonResult();
        try {
            log.info("uploadFiles 上传文件操作>>>>>id:{}", id);
            if (files != null) {
                for (MultipartFile file : files) {
                    jsonResult = demoService.uploadFiles(file, id);
                }
            } else {
                return jsonResult;
            }
        } catch (Exception e) {
            log.error("uploadFiles>>>>异常:{}", e.toString());
        }
        log.info("uploadFiles>>>>返回结果:{}", res);
        return jsonResult;
    }
Service上传实现

if(OSname.toUpperCase().contains(“windows”.toUpperCase())){//windows系统下路径
path = “D:/upload/”+ date + “/” +fileName;
}else{
path = fileRelationPath+ date + “/” + fileName;
}
File localFile = new File(path);
if (!localFile.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
localFile.getParentFile().mkdirs();
}
file.transferTo(localFile);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
简单的利用javajs实现文件上传 package com.fendou.myString; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUpload extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean a=ServletFileUpload.isMultipartContent(request); if(a){ FileItemFactory factory=new DiskFileItemFactory(); ServletFileUpload upload=new ServletFileUpload (factory); Iterator items; try{ items=upload.parseRequest (request).iterator(); while(items.hasNext()){ FileItem item=(FileItem) items.next(); if(!item.isFormField()){ String name=item.getName (); String fileName=name.substring(name.lastIndexOf("\\")+1, name.length()); String path=request.getRealPath("file")+File.pathSeparatorChar+fileName; File uploadFile=new File (path); request.getSession ().setAttribute("file", uploadFile); item.write(uploadFile); response.setContentType ("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out=response.getWriter(); // out.print("<font size='2'> 上传的文件为:"+name+"<br>"); // out.print("保存在服务器上 的地址为:"+path+"</font>"); } } }catch(Exception e){ e.printStackTrace(); } } response.sendRedirect("smartupload.jsp"); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值