java中ajax实现文件上传下载

来源:互联网 发布:得无异乎的异 编辑:程序博客网 时间:2024/06/05 07:31

上传前台html:注意type不要用submit

<form id="upload-form"   method="post" enctype="multipart/form-data" >

                                    <div class="modal-body">
                                        <input type="file" name="myFile"/>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-default" data-dismiss="modal"> 取消</button>
                                        <button type="button" onclick="updownload.upload()" class="btn btn-primary" >上传</button>
</div>

</form>

上传前台js:注意用formData定义文件流才可以使用ajax上传

updownload.upload=function(){
var formData = new FormData(document.getElementById("upload-form"));  
    $.ajax({  
         url: "updownload/upload",  
         method: 'POST',  
         data: formData,   
         contentType: false,  
         processData: false,  
         success: function (resp) {
        if(resp.result==1){
$('#myModal').modal('hide');
comm.showSuccessToast("上传成功");//成功提示
}else{
comm.showFailToast("上传失败");//失败提示
}
        updownload.searchList();
         }
    });
}

上传后台:

@RequestMapping(value ="/upload",method = RequestMethod.POST)
@ResponseBody
    public RespJson upload(@RequestParam MultipartFile myFile, HttpSession session) throws IOException {
        //获得原来文件名(含后缀名)
        String originalFilename = myFile.getOriginalFilename();
        int pos = originalFilename.lastIndexOf(".");
        //原文件后缀名
        String suffix = originalFilename.substring(pos);
        //保存文件
        //ServletContext application = session.getServletContext();
        //String realPath = application.getRealPath("D:\\workspace111\\ycpolice-web\\web\\static\\updownload");
        String realPath = "D:\\workspace111\\ycpolice-web\\web\\static\\updownload";
        //产生一个uuid随机文件名
        String uuid = UUID.randomUUID().toString();
        String fullPath = realPath + File.separator + uuid + suffix;
        InputStream in = null;
try {
in = myFile.getInputStream();
OutputStream out = new FileOutputStream(new File(fullPath));


int len = 0;
byte[] buf = new byte[3 * 1024];
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
in.close();


} catch (IOException e) {
e.printStackTrace();
}


        
        //数据库插入数据
        TUpdownloadEntity upload=new TUpdownloadEntity();
        upload.setFileName(uuid+suffix);
        updownloadService.save(upload);
        


        return RespJsonFactory.buildSuccess();
    }

下载前台:

只需要传你要下载的文件名就可以了

下载后台:

@RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downLoad(HttpServletRequest request, HttpServletResponse response,String fileName) {
        //String realPath = request.getSession().getServletContext().getRealPath("D:\\workspace111\\ycpolice-web\\web\\static\\updownload");
        String realPath = "D:\\workspace111\\ycpolice-web\\web\\static\\updownload";
        //获得服务器端某个文件的完整路径
        String fullPath = realPath + File.separator + fileName;
        //设置响应
        response.setContentType("application/force-download");
        //设置响应头信息
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);// 设置文件名;

       //文件名有中文时设置编码

       //response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("GBK"),"ISO-8859-1"));

       try {
            File downloadFile = new File(fullPath);
            FileInputStream inputStream = new FileInputStream(downloadFile);
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


原创粉丝点击