java後台怎麼拿到上傳的文件

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class EntityServlet1 extends HttpServlet {

private static final long serialVersionUID = 1L;
private String uploadPath = "D:\\temp"; // 上傳文件的目錄
File tempPathFile;

// 重寫doPost方法,處理事件識別請求
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();

// Set factory constraints
factory.setSizeThreshold(4096); // 設置緩沖區大小,這里是4kb
factory.setRepository(tempPathFile);// 設置緩沖區目錄

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Set overall request size constraint
upload.setSizeMax(4194304); // 設置最大文件尺寸,這里是4MB

List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
Iterator<FileItem> i = items.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
if (fileName != null) {
File fullFile = new File(new String(fi.getName().getBytes(), "utf-8")); // 解決文件名亂碼問題
File savedFile = new File(uploadPath, fullFile.getName());
fi.write(savedFile);
}
}
System.out.print("upload succeed");
} catch (Exception e) {

}
}
}

㈡ java怎麼實現上傳附件的功能

上傳附件,實際上就是將文件存儲到遠程伺服器,進行臨時存儲。舉例:
**
* 上傳文件
*
* @ fileName
* @param plainFilePath 文件路徑路徑
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上傳文件開始");
Log.info("連接遠程上傳伺服器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");
}
}
Log.info("檢查文件路徑是否存在:/"+filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查詢文件路徑不存在:"+"/"+filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 設置文件類型(二進制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上傳文件成功:"+fileName+"。文件保存路徑:"+"/"+filepath+"/");
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
備註:只需要修改上傳的伺服器地址、用戶名、密碼即可進行伺服器訪問上傳。根據實際需要修改即可。

㈢ java中怎麼把文件上傳到伺服器的指定路徑

String realpath = ServletActionContext.getServletContext().getRealPath("/upload") ;//獲取伺服器路徑
String[] targetFileName = uploadFileName;
for (int i = 0; i < upload.length; i++) {
File target = new File(realpath, targetFileName[i]);
FileUtils.File(upload[i], target);
//這是一個文件復制類File()裡面就是IO操作,如果你不用這個類也可以自己寫一個IO復制文件的類
}

其中private File[] upload;// 實際上傳文件

private String[] uploadContentType; // 文件的內容類型

private String[] uploadFileName; // 上傳文件名

這三個參數必須這樣命名,因為文件上傳控制項默認是封裝了這3個參數的,且在action裡面他們應有get,set方法

㈣ java怎麼把文件傳輸到file

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;temp<ERRORTYPE.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+" ");
}
。。。。。。
這樣就實現了上傳文件至資料庫

㈤ java怎樣上傳圖片(寫個例子謝謝);

我有一段上傳圖片的代碼,並且可以根據實際,按月或按天等,生成存放圖片的文件夾
首先在JSP上放一個FILE的標簽這些我都不說了,你也一定明白,我直接把處理過程給你發過去
我把其中存到資料庫中的內容刪除了,你改一下就能用
/**
*
* 上傳圖片
* @param servlet
* @param request
* @param response
* @return
* @throws Exception
*/

//這里我是同步上傳的,你隨意
public synchronized String importPic(HttpServlet servlet, HttpServletRequest request,HttpServletResponse response) throws Exception {
SimpleDate()Format formatDate() = new SimpleDate()Format("yyyyMM");
Date nowtime=new Date();
String formatnowtime=formatDate.format(nowtime);
File root = new File(request.getRealPath("/")+"uploadfile/images/"+formatnowtime+"/"); //應保證在根目錄中有此目錄的存在 如果沒有,下面則上創建新的文件夾

if(!root.isDirectory())
{
System.out.println("創建新文件夾成功"+formatnowtime);
root.mkdir();
}
int returnflag = 0;
SmartUpload mySmartUpload =new SmartUpload();
int file_size_max=1024000;
String ext="";
String url="uploadfile/images/"+formatnowtime+"/";

// 只允許上載此類文件
try{
// 初始化
mySmartUpload.initialize(servlet.getServletConfig(),request,response);
mySmartUpload.setAllowedFilesList("jpg,gif,bmp,jpeg,png,JPG");
// 上載文件

mySmartUpload.upload();
} catch (Exception e){
response.sendRedirect()//返回頁面
}

com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
if (myFile.isMissing()){ //沒有選擇圖片做提示!
returnflag = 3;
}else{
String myFileName=myFile.getFileName(); //取得上載的文件的文件名
ext= myFile.getFileExt(); //取得後綴名
if(ext.equals("jpg")||ext.equals("gif")||ext.equals("bmp")||ext.equals("jpeg")||ext.equals("png")||ext.equals("JPG")){ //jpeg,png不能上傳!)
int file_size=myFile.getSize(); //取得文件的大小
String saveurl="";
if(file_size<file_size_max){
try{
//我上面說到,把操作資料庫的代友刪除了,這里就應該是判斷,你的圖片是不是已經存在了,存在要怎麼處理,不存在要怎麼處了,就是你的事了 }
//更改文件名,取得當前上傳時間的毫秒數值
Calendar calendar = Calendar.getInstance();
//String filename = String.valueOf(calendar.getTimeInMillis());
String did = contractBean.getMaxSeq("MULTIMEDIA_SEQ");
String filename = did;
String flag = "0";
String path = request.getRealPath("/")+url;
String ename = myFile.getFileExt();
//.toLowerCase()轉換大小寫
saveurl=request.getRealPath("/")+url;
saveurl+=filename+"."+ext; //保存路徑
myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);
//將圖片信息插入到資料庫中
// ------上傳完成,開始生成縮略圖-----
java.io.File file = new java.io.File(saveurl); //讀入剛才上傳的文件
String newurl=request.getRealPath("/")+url+filename+"_min."+ext; //新的縮略圖保存地址
Image src = javax.imageio.ImageIO.read(file); //構造Image對象
float tagsize=200;
int old_w=src.getWidth(null);
int old_h=src.getHeight(null);
int new_w=0;
int new_h=0;
int tempsize;
float tempdouble;
if(old_w>old_h){
tempdouble=old_w/tagsize;
}else{
tempdouble=old_h/tagsize;
}
// new_w=Math.round(old_w/tempdouble);
// new_h=Math.round(old_h/tempdouble);//計算新圖長寬
new_w=150;
new_h=110;//計算新圖長寬
BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //繪制縮小後的圖
FileOutputStream newimage=new FileOutputStream(newurl); //輸出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag); //近JPEG編碼
newimage.close();
returnflag = 1;
}else{
returnflag = 0;
System.out.println("('上傳文件大小不能超過"+(file_size_max/1000)+"K');");
}
}else{
returnflag = 2;
}
}
response.sendRedirect();
return "11";
}

㈥ 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;temp<ERRORTYPE.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+" ");

  • }

  • 。。。。。。

  • 這樣就實現了上傳文件至資料庫

㈦ 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如何實現文件上傳

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怎麼上傳大文件

  1. 前端采復用dropzone可拖拽多制文件上傳,後端採用MultipartFile接收。

  2. getBytes方法會一次載入所有數據,會導致內存溢出。解決辦法就是開辟一小塊內存如1024byte,以流的形式循環讀取上傳的數據,再輸出文件。

  3. 彈出文件選擇框。這里選擇一個4個多G的安裝文件。

  4. 最後看到文件上傳完畢,可以看到文件是4.3個G。

  5. 再看一下網站後台磁碟,upload文件夾中已經有該安裝文件。

㈩ 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;temp<ERRORTYPE.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+" ");

  • }

  • 。。。。。。

  • 這樣就實現了上傳文件至資料庫