Java實現文件的上傳下載(含源代碼和jar包)


1.需要使用的jar包

 

鏈接:https://pan.baidu.com/s/1IaxQRSwfzxDpe4w4JiaEKw
提取碼:xwtz

 

2.如果想實現文件的下載,需要創建一張表,表的結構為

id url(id為查找依據,url為文件名即可)

 

 2.文件的上傳

該方法我是建立在SpringBoot框架中實現的,實際上這並不是必要的。

主要的是參數file是上傳的文件信息,即路徑相關。path的路徑為獲取的,使用與linux與windows系統,如果服務器固定,可以將path路徑寫成絕對路徑。

上傳之后需要將文件名存進數據庫中,並且對應唯一的id方便下載使用。

后台

@RequestMapping("upload")
    public String testupload(@RequestParam("uploadfile") MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException{
        System.out.println("上傳");
        if(!file.isEmpty()) {//上傳文件路徑
            String path = request.getSession().getServletContext().getRealPath(File.separator+"WEB-INF"+File.separator+"testupload");
        //path="H:"+File.separator+"Demo"; 如果寫絕對路徑可用這個path覆蓋上邊
//上傳文件名 String filename = file.getOriginalFilename(); File filepath = new File(path,filename); //判斷路徑是否存在,如果不存在就創建一個 if (!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs(); } //將上傳文件保存到一個目標文件當中 file.transferTo(new File(path + File.separator + filename)); userService.insertFileByFileName(filename); //將文件的名字存入數據庫 //輸出文件上傳最終的路徑 測試查看 return String.valueOf(file.getSize()); } else { return "0"; } }

前台

<form id="fileform" method="post" enctype="multipart/form-data">
<input type="file" id="fileupload" name="uploadfile"/>
<button id="upload_btn">上傳文件</button>
</form>


$("#upload_btn").click(function(){
var form = new FormData(document.getElementById("fileform"));
    $.ajax({
        type:"post",
        url:"/user/upload",
        data:form,
        processData:false,
        contentType:false,
        dataType:'text',
        success:function(data){
                alert(data);
        }
    });
});

 

 

3.文件的下載(注)

ids為傳入的參數,為數據庫中對應文件名的id,根據id查找到文件名,

path為上傳的文件路徑,然后將路徑與文件名拼接輸出路徑即為下載路徑。

注:下載的請求不能使用ajax,具體原因不清楚,我使用ajax多次嘗試失敗,改用a標簽直接請求然后成功。

后台

@RequestMapping(value = "downloadfile",produces = "application/json;charset=utf-8")
    public void downloadlm(HttpServletRequest request,HttpServletResponse response,String ids,Model model) throws IOException {
        int id=Integer.parseInt(ids);
        System.out.println("進入下載文件");
        Myfile myFile = userService.selectFileById(id);
        
        String path = request.getSession().getServletContext().getRealPath(File.separator+"WEB-INF"+File.separator+"testupload");
        path="H:"+File.separator+"Demo";
        String filename=myFile.getUrl().substring(myFile.getUrl().lastIndexOf("\\")+1);    
        System.out.println(filename+"=======================================");
        File file = new File(path+File.separator+filename);
        System.out.println(file.getPath());
        //設置響應的頭信息,解決文件名為中文亂碼的問題
        response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(file.getName(), "utf-8"));
        //使用文件輸入流讀取下載文件信息
        FileInputStream in = new FileInputStream(file);
        //得到響應流中的輸出流
        OutputStream out = response.getOutputStream();
        //建立一個緩存區
        byte[] buffer = new byte[1024];
        
        int len = 0;
        //把輸入流中的數據通過循環寫入到響應流中
        while((len = in.read(buffer)) > 0) {
            out.write(buffer,0,len);
        }
        
        
        in.close();
        out.close();
        
    }

前台:

<a id="down_file_btn"  href="/user/downloadfile?ids=1">下載</a>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM