1. 程式人生 > >HTML form表單資料與檔案混合上傳

HTML form表單資料與檔案混合上傳

將頁面提交檔案上傳到伺服器目錄下面(只能是POST提交方式)
需要引入commons-fileupload.jar

form表單例子如下


<form action="user.do?op=updateUserImage" id="upfile"  method="post" enctype="multipart/form-data">
     <input id="fuserid" type="hidden" name="id" value="12334" />
     <input id="newuserimage" name="newuserimage"
value="瀏覽圖片" type="file" /> <input type="submit" value="tijiao"/> </form>

檔案上傳

package com.xu.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import
java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import
org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @SuppressWarnings(value="all") public class UploadFile { private static String fileNmae=""; /** * 隨機資料夾名 * @return */ private String randomFilePath(){ SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd/HH"); return format.format(new Date()).replace("/", File.separator)+File.separator; } /** * 隨機檔名 * @return */ private String randomFileName(){ fileNmae= UUID.randomUUID().toString().substring(0,10); return fileNmae; } private String getFileName(String name){ return name.substring(name.lastIndexOf(".")); } /** * 單檔案上傳 * @param request HttpServletRequest * @param directories 在 Tomcat webapps 下面的存放檔案的資料夾的資料夾名 * @return * @throws FileUploadException * @throws IOException * @throws ServletException */ public FileBean singleFileUpload(HttpServletRequest request,String directories) throws FileUploadException, IOException, ServletException{ request.setCharacterEncoding("UTf-8"); String realPath=new File(request.getRealPath("/")).getParent()+File.separator+directories+File.separator+randomFilePath(); randomFileName();//獲取隨機檔名 String webPath=directories+File.separator+randomFilePath()+fileNmae; DiskFileItemFactory factory=new DiskFileItemFactory(1024*30,new File(realPath));//建立檔案目錄 ServletFileUpload fileUpload=new ServletFileUpload(factory); List<FileItem> list = fileUpload.parseRequest(request); FileBean bean=new FileBean(); for(FileItem item:list){ if(!item.isFormField()){//說明是檔案型別 realPath+=fileNmae+getFileName(item.getName()); webPath+=getFileName(item.getName()); bean.setFileType(item.getContentType()); bean.setFileSize(item.getSize()); bean.setRealPath(realPath); bean.setWebPath(webPath); bean.setOriginName(item.getName()); bean.setNewName(fileNmae+getFileName(item.getName())); InputStream read=item.getInputStream(); OutputStream write=new FileOutputStream(realPath); byte[] bt = new byte[1024]; int len=0; while((len=read.read(bt))!=-1){ write.write(bt, 0, len); } write.flush(); write.close(); read.close(); item.delete(); break; } } return bean; } /** * 多檔案上傳 * @param request HttpServletRequest * @param directories directories 在 Tomcat webapps 下面的存放檔案的資料夾的資料夾名 * @return * @throws FileUploadException * @throws IOException */ public List<FileBean> multiFileUpload(HttpServletRequest request,String directories) throws FileUploadException, IOException{ request.setCharacterEncoding("UTf-8"); String realPath=new File(request.getRealPath("/")).getParent()+File.separator+directories+File.separator+randomFilePath(); String webPath=directories+File.separator+randomFilePath(); DiskFileItemFactory factory=new DiskFileItemFactory(1024*30,new File(realPath));//建立檔案目錄 ServletFileUpload fileUpload=new ServletFileUpload(factory); List<FileItem> list = fileUpload.parseRequest(request); List<FileBean> filelist=new ArrayList<FileBean>(); FileBean bean=null; for(FileItem item:list){ if(!item.isFormField()){//說明是檔案型別 randomFileName();//獲取隨機檔名 bean=new FileBean(); realPath+=fileNmae+getFileName(item.getName()); webPath+=fileNmae+getFileName(item.getName()); bean.setFileType(item.getContentType()); bean.setFileSize(item.getSize()); bean.setRealPath(realPath); bean.setWebPath(webPath); bean.setOriginName(item.getName()); bean.setNewName(fileNmae+getFileName(item.getName())); InputStream read=item.getInputStream(); OutputStream write=new FileOutputStream(realPath); byte[] bt = new byte[1024]; int len=0; while((len=read.read(bt))!=-1){ write.write(bt, 0, len); } write.flush(); write.close(); read.close(); item.delete(); filelist.add(bean); } } return filelist; } }

檔案上傳Bean

package com.xu.utils;

import java.io.Serializable;

public class FileBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 8999004458855350561L;


    private String fileType;
    private String originName;
    private String realPath;
    private String webPath;
    private String newName;
    private Long fileSize;
    public String getFileType() {
        return fileType;
    }
    public void setFileType(String fileType) {
        this.fileType = fileType;
    }
    public String getOriginName() {
        return originName;
    }
    public void setOriginName(String originName) {
        this.originName = originName;
    }
    public String getRealPath() {
        return realPath;
    }
    public void setRealPath(String realPath) {
        this.realPath = realPath;
    }
    public String getWebPath() {
        return webPath;
    }
    public void setWebPath(String webPath) {
        this.webPath = webPath;
    }
    public String getNewName() {
        return newName;
    }
    public void setNewName(String newName) {
        this.newName = newName;
    }
    public Long getFileSize() {
        return fileSize;
    }
    public void setFileSize(Long fileSize) {
        this.fileSize = fileSize;
    }
    @Override
    public String toString() {
        return "FileBean [fileType=" + fileType + ", originName=" + originName + ", realPath=" + realPath
                + ", webPath=" + webPath + ", newName=" + newName + ", fileSize=" + fileSize + "]";
    }   
}

相關推薦

HTML form資料檔案混合

將頁面提交檔案上傳到伺服器目錄下面(只能是POST提交方式) 需要引入commons-fileupload.jar form表單例子如下 <form action="user.do?op=updateUserImage" id="upfile"

工作中如何使用ajax提交form,包括ajax文件

msu 包括 需要 java tip ror 存儲 adf ucc 提供一種方法就是利用jquery.form.js,我們是和java對接的後臺。 代碼如下: <input type="text" id="text1"> <input type="text

JSP—資訊圖片同時

// Check that we have a file upload request 檢查是否是表單檔案上請求 boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Crea

趴一趴如何用最簡單的方式從html form中獲取到資料

最近網速一直不太好 ~~~不開心 本文采用的是最簡單的方式,僅供自己試驗,畢竟存在一些不安全因素。 看了其他好的的方式發現都太麻煩,所以自己總結下。 是這樣的:input.html頁面中有一段程式碼。

springMVC實現form資料+檔案提交

說明: 1、SpringMVC實現檔案上傳,需要再新增兩個jar包。一個是檔案上傳的jar包,一個是其所依賴的IO包。這兩個jar包 commons-fileupload-1.2.2.jar commons-io-2.4.jar Controller @Respon

html form提交資料並後臺獲取

http://www.tuicool.com/articles/m67vMbQ 前臺: HTML的程式碼:(關鍵是要在form裡設定enctype="multipart/form-data",這樣才能在提交表單時,將檔案以二進位制流的形式傳輸到伺服器) <ht

HTML——form中常用標簽總結

radio led ext only pin sta word htm and 1 <form action="" method="get"> 2 <!-- 3 placeholder="請輸

iframe標籤實現form提交下載檔案

一、表單提交的程式碼常規寫法 <iframe name="testIframeName" style="display:none;"></iframe> <form target="testIframeName" method="post" acti

html--form常用操作

form表單 用於收集使用者資訊,如:登入、註冊等場景;所有要提交的資料都必須放在form標籤中<form action=" "  method=" ">   action:提交地址、動作,與input標籤中typy標籤的submit屬性相關聯。  <inp

React中Form資料獲取

const { getFieldDecorator } = this.props.form; this.getFieldsValue = this.props.form.getFieldsValue;//獲得表單所有控制元件的值 this.props.form.getFieldsValue(

form提交ajax提交的區別

原文地址:https://blog.csdn.net/yao302789/article/details/50954902 Ajax提交是通過js來提交請求,請求與響應均由js引擎來處理,頁面不會重新整理,用 戶感覺不到實際上瀏覽器發出了請求。比如說我們希望網頁總是顯示最新的新聞, 而又不想老是

Servlet 獲取前端Form資料,並實現請求重定向、請求轉發

1.前端介面 編寫一個最簡單的登入介面: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title&g

formset批量處理form資料

Formset(表單集)是多個表單的集合。Formset在Web開發中應用很普遍,它可以讓使用者在同一個頁面上提交多張表單,一鍵新增多個數據 class StudentStudyRecordModel(forms.ModelForm): class Meta: model=St

@ModelAttribute獲取POST請求的FORM資料

1.JSP表單如下: <form method="post" action="hao.do"> a: <input id="a" type="text" name="a" /> b: <input id="b" type="text" nam

vue.js v-model雙向資料繫結, vue.js form資料繫結

vue.js v-model雙向資料繫結, vue.js form表單資料繫結   ================================ ©Copyright 蕃薯耀 2018年11月29日 http://fanshuyao.iteye.com/   &l

html form提交前驗證

可以使用form表單的onsubmit方法,在提交表單之前,對錶單或者網頁中的資料進行檢驗。 onsubmit指定的方法返回true,則提交資料;返回false不提交資料。   <HTML> <head> <meta htt

html form驗證和使用者體驗程式碼

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>改善使用者體驗的表單</title> <style

淺談web工程中BeanUtils的封裝MyBeanUtils,populate方法使用 【接收前端form資料

宣告本測試使用JDK9,Tomcat9.0.10 ,IDEA2018.2  ; 淺談  BeanUtils 的封裝 , BeanUtils  類中方法  populate  (Object  be

關於request無法獲取到前端傳送的form資料

問題:servlet中使用request.getParameter()獲取不到前端傳送的form表單資料 post請求是接收到了的,但是輸出一直是"null",資料為空,本來一直以為是後臺寫錯了 protected void doPost(HttpServletReque

HTML form中action的正確寫法

mapping oca http context java ica 現在 ont ext   我的Java Web Application的context是myweb,即http://localhost:8080/myweb/index.jsp是歡迎頁。   現在我的一個C