服務器端 文件上傳模版代碼

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        List types = Arrays.asList("jpg","gif","avi","txt");

        try{
            DiskFileItemFactory factory = new DiskFileItemFactory();  //10k
            factory.setSizeThreshold(1024*1024);
            factory.setRepository(new File(this.getServletContext().getRealPath("/temp")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setProgressListener(new ProgressListener(){
                public void update(long pBytesRead, long pContentLength, int pItems) {
                    System.out.println("當前已解析:" + pBytesRead);
                }
            });

            upload.setFileSizeMax(1024*1024*5);
            if(!upload.isMultipartContent(request)){
                //按照傳統方式獲取表單數據
                request.getParameter("username");
                return;
            }
            upload.setHeaderEncoding("UTF-8");
            List<FileItem> list = upload.parseRequest(request);

            for(FileItem item : list){
                if(item.isFormField()){
                    //爲普通輸入項
                    String inputName = item.getFieldName();
                    String inputValue = item.getString("UTF-8");
                    //inputValue = new String(inputValue.getBytes("iso8859-1"),"UTF-8");
                    System.out.println(inputName + "="  + inputValue);
                }else{
                    String filename = item.getName().substring(item.getName().lastIndexOf("\\")+1);  //""
                    if(filename==null || filename.trim().equals("")){
                        continue;
                    }

                    /*String ext = filename.substring(filename.lastIndexOf(".")+1);
                    if(!types.contains(ext)){
                        request.setAttribute("message", "本系統不支持" + ext + "這種類型");
                        request.getRequestDispatcher("/message.jsp").forward(request, response);
                        return;
                    }*/
                    InputStream in = item.getInputStream();
                    int len = 0;
                    byte buffer[] = new byte[1024];
                    String saveFileName = generateFileName(filename);
                    String savepath = generateSavePath(this.getServletContext().getRealPath("/WEB-INF/upload"),saveFileName);
                    FileOutputStream out = new FileOutputStream(savepath + File.separator + saveFileName);
                    while((len=in.read(buffer))>0){
                        out.write(buffer, 0, len);
                    }
                    in.close();
                    out.close();
                    item.delete();  //刪除臨時文件
                }
            }
        }catch (FileUploadBase.FileSizeLimitExceededException e) {
            request.setAttribute("message", "文件大小不能超過5m");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
        request.setAttribute("message", "上傳成功!!");
        request.getRequestDispatcher("/message.jsp").forward(request, response);
    }

    //
    public String generateSavePath(String path,String filename){
        int hashcode = filename.hashCode();  //121221
        int dir1 = hashcode&15;
        int dir2 = (hashcode>>4)&0xf;

        String savepath = path + File.separator + dir1 + File.separator + dir2;
        File file = new File(savepath);
        if(!file.exists()){
            file.mkdirs();
        }
        return savepath;
    }

    public String generateFileName(String filename){
        //83434-83u483-934934
        return UUID.randomUUID().toString() + "_" + filename;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

jdbc 應用的事務管理

ThreadLocal:可以在線程範圍內實現數據共享.

jdbc多表操作

儘量不用一對多關係

文件上傳注意事項

1.上傳文件中文亂碼問題:
1.1解決文件的亂碼
ServletFileUpload upload=new ServletFileUpload( factory );
upload.setHeaderEncoding( ” UTF-8 ” );
1.2解決普通輸入項的亂碼
注意:表單類型爲multipart/form-data的時候,設置request的編碼是無效的

String inputValue=new String( inputValue.getBytes(" iso8859-1 ")," UTF-8 ");  

String inputValue=item.getString( " UTF-8 " );

2.在處理表單之前,要記得調用:
ServletFileUpload.isMultipartContent方法判斷提交表單的類型,如果該方法返回true,則按上傳方式處理,否則按照傳統方式處理表單即可

3.設置解析器緩衝區的大小,以及臨時文件的刪除
設置解析器緩衝區的大小 DiskFileItemFactory.setSizeThreshold(1024*1024);
臨時文件的刪除:在程序中處理完上傳文件後,一定要記得調用item.delete()方法,以刪除臨時文

4.在做上傳系統時,千萬要注意上傳文件的保存目錄,這個上傳文件的保存目錄絕對不能讓外界直接訪問到。

5.限制上傳文件的類型
在處理上傳文件時,判斷上傳文件的後綴名是不是允許的

6.限制上傳文件的大小
調用解析器的ServletFileUpload.setFileSizeMax(1024*1024*5);就可以限制上傳文件的大小,如果上傳文件超出限制,則解析器會拋FileUploadBase.FileSizeLimitExceededException異常,程序員通過是否抓到這個異常,進而就可以給用戶友好提示。

7.如何判斷空的上傳輸入項
String filename = item.getName().substring(item.getName().lastIndexOf(“\”)+1); //””
if(filename==null || filename.trim().equals(“”)){
continue;
}

8、爲避免上傳文件的覆蓋,程序在保存上傳文件時,要爲每一個文件生成一個唯一的文件名
public String generateFileName(String filename){
//83434-83u483-934934
return UUID.randomUUID().toString() + “_” + filename;
}

9、爲避免在一個文件夾下面保存超過1000個文件,影響文件訪問性能,程序應該把上傳文件打散後存儲。
public String generateSavePath(String path,String filename){
int hashcode = filename.hashCode(); //121221
int dir1 = hashcode&15;
int dir2 = (hashcode>>4)&0xf;

    String savepath = path + File.separator + dir1 + File.separator + dir2;
    File file = new File(savepath);
    if(!file.exists()){
        file.mkdirs();
    }
    return savepath;
}

10、監聽上傳進度
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(new ProgressListener(){
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println(“當前已解析:” + pBytesRead);
}
});

11、在web頁面中添加動態上傳輸入項

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章