本文目錄一覽:
JAVA WEB文件上傳步驟
JAVA WEB文件上傳步驟如下:
實現 Web 開發中的文件上傳功能,兩個操作:在 Web 頁面添加上傳輸入項,在 Servlet 中讀取上傳文件的數據並保存在本地硬碟中。
1、Web 端上傳文件。在 Web 頁面中添加上傳輸入項:input type=”file” 設置文件上傳輸入項時應注意:(1) 必須設置 input 輸入項的 name 屬性,否則瀏覽器將不會發送上傳文件的數據。(2) 必須把 form 的 enctype 屬性設為 multipart/form-data,設置該值後,瀏覽器在上傳文件時,將把文件數據附帶在 http 請求消息體中,並使用 MIME 協議對上傳文件進行描述,以方便接收方對上傳數據進行解析和處理。(3) 表單提交的方式要是 post
2、伺服器端獲取文件。如果提交表單的類型為 multipart/form-data 時,就不能採用傳統方式獲取數據。因為當表單類型為 multipart/form-data 時,瀏覽器會將數據以 MIME 協議的形式進行描述。如果想在伺服器端獲取數據,那麼我們必須採用獲取請求消息輸入流的方式來獲取數據。
3、Apache-Commons-fileupload。為了方便用戶處理上傳數據,Apache 提供了一個用來處理表單文件上傳的開源組建。使用 Commons-fileupload 需要 Commons-io 包的支持。
4、fileuplpad 組建工作流程
(1)客戶端將數據封裝在 request 對象中。
(2)伺服器端獲取到 request 對象。
(3)創建解析器工廠 DiskFileItemFactory 。
(4)創建解析器,將解析器工廠放入解析器構造函數中。之後解析器會對 request 進行解析。
(5)解析器會將每個表單項封裝為各自對應的 FileItem。
(6)判斷代表每個表單項的 FileItem 是否為普通表單項 isFormField,返回 true 為普通表單項。
(7)如果是普通表單項,通過 getFieldName 獲取表單項名,getString 獲得表單項值。
(8)如果 isFormField 返回 false 那麼是用戶要上傳的數據,可以通過 getInputStream 獲取上傳文件的數據。通過getName 可以獲取上傳的文件名。
java中怎樣上傳文件
Java代碼實現文件上傳
FormFile file=manform.getFile();
String newfileName = null;
String newpathname=null;
String fileAddre=”/numUp”;
try {
InputStream stream = file.getInputStream();// 把文件讀入
String filePath = request.getRealPath(fileAddre);//取系統當前路徑
File file1 = new File(filePath);//添加了自動創建目錄的功能
((File) file1).mkdir();
newfileName = System.currentTimeMillis()
+ file.getFileName().substring(
file.getFileName().lastIndexOf(‘.’));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath + “/”
+ newfileName);
newpathname=filePath+”/”+newfileName;
System.out.println(newpathname);
// 建立一個上傳文件的輸出流
System.out.println(filePath+”/”+file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);// 將文件寫入伺服器
}
bos.close();
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
java如何實現文件上傳
public static int transFile(InputStream in, OutputStream out, int fileSize) {
int receiveLen = 0;
final int bufSize = 1000;
try {
byte[] buf = new byte[bufSize];
int len = 0;
while(fileSize – receiveLen bufSize)
{
len = in.read(buf);
out.write(buf, 0, len);
out.flush();
receiveLen += len;
System.out.println(len);
}
while(receiveLen fileSize)
{
len = in.read(buf, 0, fileSize – receiveLen);
System.out.println(len);
out.write(buf, 0, len);
receiveLen += len;
out.flush();
}
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
return receiveLen;
}
這個方法從InputStream中讀取內容,寫到OutputStream中。
那麼發送文件方,InputStream就是FileInputStream,OutputStream就是Socket.getOutputStream.
接受文件方,InputStream就是Socket.getInputStream,OutputStream就是FileOutputStream。
就OK了。 至於存到資料庫里嘛,Oracle里用Blob。搜索一下,也是一樣的。從Blob能獲取一個輸出流。
java中怎麼把文件上傳到伺服器的指定路徑?
文件從本地到伺服器的功能,其實是為了解決目前瀏覽器不支持獲取本地文件全路徑。不得已而想到上傳到伺服器的固定目錄,從而方便項目獲取文件,進而使程序支持EXCEL批量導入數據。
java中文件上傳到伺服器的指定路徑的代碼:
在前台界面中輸入:
form method=”post” enctype=”multipart/form-data” action=”../manage/excelImport.do”
請選文件:input type=”file” name=”excelFile”
input type=”submit” value=”導入” onclick=”return impExcel();”/
/form
action中獲取前台傳來數據並保存
/**
* excel 導入文件
* @return
* @throws IOException
*/
@RequestMapping(“/usermanager/excelImport.do”)
public String excelImport(
String filePath,
MultipartFile excelFile,HttpServletRequest request) throws IOException{
log.info(“action:{} Method:{} start”,”usermanager”,”excelImport” );
if (excelFile != null){
String filename=excelFile.getOriginalFilename();
String a=request.getRealPath(“u/cms/www/201509”);
SaveFileFromInputStream(excelFile.getInputStream(),request.getRealPath(“u/cms/www/201509”),filename);//保存到伺服器的路徑
}
log.info(“action:{} Method:{} end”,”usermanager”,”excelImport” );
return “”;
}
/**
* 將MultipartFile轉化為file並保存到伺服器上的某地
*/
public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException
{
FileOutputStream fs=new FileOutputStream( path + “/”+ savefile);
System.out.println(“————“+path + “/”+ savefile);
byte[] buffer =new byte[1024*1024];
int bytesum = 0;
int byteread = 0;
while ((byteread=stream.read(buffer))!=-1)
{
bytesum+=byteread;
fs.write(buffer,0,byteread);
fs.flush();
}
fs.close();
stream.close();
}
java怎麼實現上傳文件到伺服器
common-fileupload是jakarta項目組開發的一個功能很強大的上傳文件組件
下面先介紹上傳文件到伺服器(多文件上傳):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = “text/html; charset=GB2312”;
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 設置允許用戶上傳文件大小,單位:位元組,這裡設為2m
fu.setSizeMax(2*1024*1024);
// 設置最多只允許在內存中存儲的數據,單位:位元組
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄
fu.setRepositoryPath(“c://windows//temp”);
//開始讀取上傳信息
List fileItems = fu.parseRequest(request);
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
//正則匹配,過濾路徑取文件名
String regExp=”.+////(.+)$”;
//過濾掉的文件類型
String[] errorType={“.exe”,”.com”,”.cgi”,”.asp”};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表單信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals(“”)) size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;tempERRORTYPE.LENGTH;TEMP++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+”: wrong type”);
}
}
try{
//保存上傳的文件到指定的目錄
//在下文中上傳文件至資料庫時,將對這裡改寫
item.write(new File(“d://” + m.group(1)));
out.print(name+” “+size+””);
}
catch(Exception e){
out.println(e);
}
}
else
{
throw new IOException(“fail to upload”);
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
}
}
現在介紹上傳文件到伺服器,下面只寫出相關代碼:
以sql2000為例,表結構如下:
欄位名:name filecode
類型: varchar image
資料庫插入代碼為:PreparedStatement pstmt=conn.prepareStatement(“insert into test values(?,?)”);
代碼如下:
。。。。。。
try{
這段代碼如果不去掉,將一同寫入到伺服器中
//item.write(new File(“d://” + m.group(1)));
int byteread=0;
//讀取輸入流,也就是上傳的文件內容
InputStream inStream=item.getInputStream();
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close();
out.println(name+” “+size+” “);
}
。。。。。。
這樣就實現了上傳文件至資料庫
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/198143.html