本地上傳檔案到伺服器,從伺服器下載檔案到本地

來源:互聯網
上載者:User

標籤:submit   上傳下載   修改   target   ted   eal   亂碼   tar   date()   

最近在做項目的時候涉及到了檔案的上傳、下載,以前學習IO時也沒有搞得多清楚,在網上找了些上傳下載的例子,然後修改了部分。經測試,上傳下載檔案暫時能用,下面是上傳和下載的方法:

1.本地上傳檔案到伺服器

  html代碼:

<form id="uploadDatumInfo" name="uploadDatumInfo" method="post" enctype="multipart/form-data" target="target_upload"><!-- 注意要加上:enctype="multipart/form-data"-->   <input type="file" id="datum_address" name="datum_address" class="" /> </form>

  js代碼:

function uploadDatum(){
     <!-- 驗證上傳檔案是否為空白 --> var datum_address=$("#datum_address").val(); if(datum_address==‘‘) { alert("上傳檔案不可為空!"); return; }
<!-- 提交表單資料 --> document.uploadDatumInfo.action="<%=WebConstants.WEB_ROOT%>/saveUploadMyDatum.do?&<%=MctsUtils.getURLRandom() %>"; document.uploadDatumInfo.submit();}

  後台代碼:@Controller

@Controller
public
class MyController {@Resource(name = "MyService")private MyService myService;private ResourceManager rm = ResourceManager.getInstance();//儲存上傳資料資訊@RequestMapping(value = "/saveUploadMyDatum.do")public void saveUploadMyDatum(HttpServletRequest request, HttpServletResponse response, final ModelMap context, VcDatumInfo vcDatumInfo) throws Exception { try { String myDir = rm.getValue("my_file_path"); String fileDir = rm.getValue("my_space_path"); File sourceFolder = new File(myDir + "/" + fileDir);建立隱藏檔夾 if (!sourceFolder.exists())
       { sourceFolder.mkdirs(); } String datum_address
= ""; DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(2048 * 1024); UploadProgressListener getBarListener = new UploadProgressListener(request); ServletFileUpload upload = new ServletFileUpload(factory); upload.setProgressListener(getBarListener); List<Object> formList = upload.parseRequest(request); Iterator<Object> formItem = formList.iterator(); while (formItem.hasNext())
       { FileItem item
= (FileItem) formItem.next(); if (!item.isFormField())
          {
if (item != null && item.getSize() > 0)
            { String fieldName
= item.getFieldName(); String timeTemp = String.valueOf(new Date().getTime()); String subname = item.getName().substring( item.getName().lastIndexOf(".", item.getName().length()));//擷取上傳檔案的尾碼名 String realName = item.getName().substring(0, item.getName().lastIndexOf("."));//擷取上傳檔案的檔案名稱 //System.out.println(realName); if (fieldName.equals("datum_address"))
              { datum_address
= fileDir + "/" + "datum_" + timeTemp + "_" + realName + subname;//要儲存到資料庫中的檔案地址
                
File file = new File(myDir + "/" + datum_address);//建立儲存路徑
                             item.write(file);//寫入檔案資料
                        }                     }                 } 
        }
      }
  } 
}

 2.從伺服器下載檔案

  後台代碼:  

       String myDir = rm.getValue("my_file_path");             OutputStream toClient = null;            String path = "";            path = myDir + "/" + vcDatumInfo.getDatum_address();            try {                // path是指欲下載的檔案的路徑。                File file = new File(path);                // 取得檔案名稱                String filename = file.getName();                // 取得檔案的尾碼名。                String ext = filename.substring(filename.lastIndexOf(".") + 1);                String realName = file.getName().substring(file.getName().lastIndexOf("_") + 1, file.getName().lastIndexOf("."));//取得檔案名稱,這一步得到的檔案名稱有可能不是上傳時的原檔案名稱                String realFileName = realName + "." + ext;                // 以流的形式下載檔案                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=" + java.net.URLEncoder.encode(realFileName, "UTF-8"));//注意這一步設定檔案名稱時,中文容易出現亂碼                response.addHeader("Content-Length", "" + file.length());                toClient = new BufferedOutputStream(response.getOutputStream());                response.setContentType("application/octet-stream");                toClient.write(buffer);                                vcDatumInfo.setDownload_number(vcDatumInfo.getDownload_number() + 1);                vcSpaceService.updateDatumInfo(vcDatumInfo);                            } catch (IOException ex) {                ex.printStackTrace();            }finally            {                if(toClient != null)                {                    toClient.flush();                    toClient.close();                }            }

最後,感謝分享例子的作者!

本地上傳檔案到伺服器,從伺服器下載檔案到本地

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.