1. 程式人生 > >Springmvc檔案上傳(servlet3.0)/下載(ssm)以及坑點

Springmvc檔案上傳(servlet3.0)/下載(ssm)以及坑點

  • 以前在servlet上寫過檔案上傳檔案下載,最近由於需求需要集合到ssm中,有些坑點以前都忘記了。
  • 檔案上傳:檔案上傳首先要在xml中配置上傳資訊,ssm有強大的過濾功能,你不宣告讓某種型別進來他是進不來的,我是用的是servlet3.0的part上傳檔案,省掉依賴包。 在web.xml中的springmvc配置中新增下面如下配置(配置方法可能很多,但是功能相同):
  <servlet>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</
servlet-class
>
<init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:food-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <multipart-config> <!-- <location>/</location> -->
<max-file-size>20971520</max-file-size> <!--單個檔案最大大小:20MB--> <max-request-size>20971520</max-request-size> <!--所有檔案最大大小:20MB--> <file-size-threshold>0</file-size-threshold> <!-- 超過這個大小直接存硬碟,而不是記憶體 --> </multipart-config
>
</servlet>

下面是我的下載的模板:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.food.dao.foodMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import com.food.bean.path;
@Controller
public class uploadController {
    @Autowired(required = true)
    private  foodMapper foodmapper;
    @RequestMapping(value="/onfile")
    public String uploadfile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        HttpSession session=request.getSession();
        request.setCharacterEncoding("UTF-8");//
        response.setCharacterEncoding("UTF-8");
        Part part=request.getPart("file");
        upload(part,session);
        return "sucess";

    }
    public String getname(Part part)//獲取檔名
    {
        String contentdisposition=part.getHeader("content-disposition");//form-data; name="file"; filename="jspѧϰ.txt"
        String[]filename=contentdisposition.split("=");//

        String filename1=filename[filename.length-1];//"jspѧϰ.txt"
        String filename2=filename1.replace("\"", "");
        return filename2;
    }
    public void upload(Part part, HttpSession session) throws IOException
    {

        String path=session.getServletContext().getRealPath("food/");
        //System.out.println(path);
        String filename=getname(part);
        File file=new File(path);
        if(!file.exists())//
        {
            file.mkdirs();
        }
        File file2=new File(file,filename);//
        if(!file2.exists()){file2.createNewFile();}
        InputStream in=part.getInputStream();
        OutputStream out=new FileOutputStream(file2);
        BufferedInputStream buf=new BufferedInputStream(in);
        BufferedOutputStream bufout=new BufferedOutputStream(out);
        byte by[]=new byte[1024*10];
        int q=0;
        while((q=buf.read(by))!=-1)
        {
            bufout.write(by);
            //by=new byte[1024]

        }
        bufout.close();
        buf.close();
        in.close();
        out.close();
    }

}

這個是我的一個小專案剪出來的下載模板,如果有問題修改修改就可以使用,或者可以私信我。 檔案下載:檔案上傳使用的是傳統的模板,有用sringmvc的方法的可以 檔案下載的一個大坑:當時下載中文名成發現中文名變成"–"無法顯示中文,怎麼改編碼都沒有用,後來看了百度說是tomcat的預設編碼is編碼問題,解決方法和get請求有時的亂碼解決很類似,字串重新編碼。核心是:new String(filename.getBytes(“utf-8”),“ISO8859_1”));

@RequestMapping(value = "/download")
    public String download(String filename,String path,HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println(filename);
        response.setCharacterEncoding("utf-8");
         request.setCharacterEncoding("UTF-8");
        HttpSession session=request.getSession();
        response.setContentType("text/html");
        System.out.println(filename);
        //設定檔案MIME型別
        response.setContentType(session.getServletContext().getMimeType(filename));
        //設定Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("utf-8"),"ISO8859_1"));
        String fullFileName = session.getServletContext().getRealPath( path);  //獲取絕對路徑
        System.out.println(fullFileName);
        InputStream in = new FileInputStream(fullFileName);
        BufferedInputStream buf=new BufferedInputStream(in);
        OutputStream out = response.getOutputStream();
        BufferedOutputStream ou=new BufferedOutputStream(out);
        //PrintWriter out = response.getWriter();
        int b=0;
        byte[]bite=new byte[1024];
        while((b=buf.read(bite))!=-1)
        {
            ou.write(bite);
        }
        ou.close();
        buf.close();
        in.close();
        out.close();
        return null;
    }

檔案上傳和下載一定要用buffer類,速度差別如果頻寬能夠滿足的話差別還是很大的。