1. 程式人生 > >java檔案上傳下載

java檔案上傳下載

這裡先說下spring mvc 遇到的坑,就是如果檔案上傳時,後端這樣寫public String file1(HttpServletRequest request),根據request拿到的東西是空的。所以要下面這樣寫。

上傳

在任何xml裡面(因為都要載入到的,所以可以隨便放進去)加上

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
<property name="defaultEncoding" value="UTF-8"></property>
    <property name="maxUploadSize" value="10485760" />  

cotroller裡面

@RequestMapping(value="file",method=RequestMethod.POST)
public String file1(@RequestParam("file")MultipartFile file1,HttpServletRequest request) throws IOException {
InputStream inputStream=file1.getInputStream();
//System.out.println(file1.getOriginalFilename()+" "+file1.getSize());

//第一種是原始的java檔案上傳的方式,下載的話也跟這個差不多,所以下載就不寫了;
String name=request.getSession().getServletContext().getRealPath("/")+"file";
System.out.println(name);

File file0=new File(name);
if(!file0.isDirectory()&&!file0.exists())
file0.mkdir();

name+="\\"+file1.getOriginalFilename();
File file=new File(name);
try {
file.createNewFile();
FileOutputStream outputStream;

outputStream = new FileOutputStream(file);

byte b[]=new byte[1024];
int n;
while((n=inputStream.read(b))!=-1){
outputStream.write(b, 0, n);
}
outputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
//下面是xml引入的bean,也是比較方便的方法
/*
if(!file.isEmpty()){  
            try {  
                  
                //這裡將上傳得到的檔案儲存至 d:\\temp\\file 目錄  
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File("d:/hello",   
                        System.currentTimeMillis()+ file.getOriginalFilename()));  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }
*/
return "upload";
}

檔案下載一般會涉及特定資料夾下的搜尋檔案(用迭代方法)

import java.io.File;
public class test {
 public static void main(String[] args) {
  String path="D:/hello/";
  File file=new File(path);
  researchfile(file);
  
   
 }
 public static void researchfile(File file) {  
     if (file.isDirectory()) {  
         File[] filearry = file.listFiles();  
         for (File f : filearry) {  
             if (f.isDirectory()) {  
                // System.out.println("0"+f.getAbsoluteFile());  
             } else {  
                 System.out.println(f.getAbsoluteFile());  
             }  
             researchfile(f);  
         }
     }
 }  
}

2018-1-17

有更好更方便的上傳方式,如下:

@RequestMapping(value = "fileupload")
    @ResponseBody
    public boolean fileupload(@RequestParam(value = "filename")MultipartFile file){
        if(file.isEmpty()){
            return false;
        }
        String name=file.getOriginalFilename();
        int Size= (int) file.getSize();
        System.out.println(name + "-->" + Size);

        String path="D:/NewFile";
        File f=new File(path+"/"+name);
        if(!f.getParentFile().exists()){
            f.getParentFile().mkdir();
        }
        try {
            file.transferTo(f); //儲存檔案
            return true;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }
看見上面紅色程式碼沒有?直接儲存檔案,不需要利用流的形式進行寫入,十分方便

然後上面都是寫一個檔案上傳時的controller,下面寫一個多檔案上傳的

/**
     * 實現多檔案上傳
     * */
    @RequestMapping(value="multifileUpload",method= RequestMethod.POST)
    public @ResponseBody boolean multifileUpload(@RequestParam(value = "filename")List<MultipartFile> files){

        if(files.isEmpty()){
            System.out.println("檔案為空");
            return false;
        }

        String path = "D:/NewFile" ;

        for(MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);

            if(file.isEmpty()){
                return false;
            }else{
                File dest = new File(path + "/" + fileName);
                if(!dest.getParentFile().exists()){ //判斷檔案父目錄是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                }catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return false;
                }
            }
        }
        return true;
    }
是不是很簡單,哈哈~

下載
下載的程式碼貼上下別人的,供參考

@RequestMapping("download")
    public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
        String filename="報名照片.jpg";
        String filePath = "D:/NewFile" ;
        File file = new File(filePath + "/" + filename);
        if(file.exists()){ //判斷檔案父目錄是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String("報名照片.jpg".getBytes("gb2312"),"ISO_8859_1"));

            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //檔案輸入流
            BufferedInputStream bis = null;

            OutputStream os = null; //輸出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
上面紅色程式碼很重要,是讓系統返回的不是頁面,而是類似檔案流的形式輸出。其次還

解決Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name) 中文顯示亂碼