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;
        }
    } 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.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) 中文显示乱码


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值