App下載

java怎么實(shí)現(xiàn)文件上傳?文件上傳方法分享!

猿友 2021-06-17 17:58:19 瀏覽數(shù) (3779)
反饋

我們應(yīng)該都有過這樣的經(jīng)歷,在網(wǎng)頁上上傳我們的文件或者照片,那么今天我們就來說說有關(guān)于:“java怎么實(shí)現(xiàn)文件上傳?”這個(gè)問題小編為大家分享了下面這些資料,大家可以做為參考希望對(duì)你們的學(xué)習(xí)有所幫助!


我們?cè)趈ava開發(fā)工具中如果要實(shí)現(xiàn)文件的上傳功能時(shí),我們需要依靠 Apache 組織的?Commons-io.jar、Commons-fileupload.jar?這兩個(gè)架包。

1.創(chuàng)建新的項(xiàng)目這邊小編給他命名為fileupdate大家可以按照自己的想法命名,將架包放在我們項(xiàng)目中的?WEB-INF/lib?文件夾下,如下圖:



2.index.jsp頁面代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>    
    <title>文件上傳</title>
  </head>
  <body>
  	<div align="center">
    <form action="UploadServlet" enctype="multipart/form-data" method="post">
    	名稱:<input name="name" /> <br>
    	上傳文件:<input name="img" type="file"/><br>
    	<input type="submit" value="提交" /> &nbsp;&nbsp;
    	<input type="reset" value="重置" />
    </form>
    </div>
  </body>
</html>

message.jsp代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>上傳文件成功</title>
  </head>
  <body>
   	<h1 align="center">上傳文件成功!</h1>
  </body>
</html>

3.UploadSerlvet代碼:

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;


public class UploadServlet extends HttpServlet {

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

		this.doPost(request, response);
	}

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

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		DiskFileItemFactory sf= new DiskFileItemFactory();//實(shí)例化磁盤被文件列表工廠
		String path = request.getRealPath("/upload");//得到上傳文件的存放目錄
		sf.setRepository(new File(path));//設(shè)置文件存放目錄
		sf.setSizeThreshold(1024*1024);//設(shè)置文件上傳小于1M放在內(nèi)存中
		String rename = "";//文件新生成的文件名
		String fileName = "";//文件原名稱
		String name = "";//普通field字段
		//從工廠得到servletupload文件上傳類
		ServletFileUpload sfu = new ServletFileUpload(sf);
		
		try {
			List<FileItem> lst = sfu.parseRequest(request);//得到request中所有的元素
			for (FileItem fileItem : lst) {
				if(fileItem.isFormField()){
					if("name".equals(fileItem.getFieldName())){
						name = fileItem.getString("UTF-8");
					}
				}else{
					//獲得文件名稱
					fileName = fileItem.getName();
					fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
					String houzhui = fileName.substring(fileName.lastIndexOf("."));
					rename = UUID.randomUUID()+houzhui;
					fileItem.write(new File(path, rename));
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.sendRedirect("message.jsp");
		out.flush();
		out.close();
	}
}

當(dāng)我們創(chuàng)建完成后一般會(huì)在web.xml自動(dòng)配置相關(guān)信息,如下圖:

web.xml文件代碼

運(yùn)行結(jié)果如下圖:

文件上傳


總結(jié):

以上就是有關(guān)于:“java怎么實(shí)現(xiàn)文件上傳?”這個(gè)問題的代碼和運(yùn)行結(jié)果,當(dāng)然如果你有更好的方法也可以和大家一起分享學(xué)習(xí),更多有關(guān)于java的學(xué)習(xí)內(nèi)容的知識(shí)我們都可以在java 教程中進(jìn)行學(xué)習(xí)。


0 人點(diǎn)贊