Ⅰ 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代碼實現文件上傳
FormFilefile=manform.getFile();
StringnewfileName=null;
Stringnewpathname=null;
StringfileAddre="/numUp";
try{
InputStreamstream=file.getInputStream();//把文件讀入
StringfilePath=request.getRealPath(fileAddre);//取系統當前路徑
Filefile1=newFile(filePath);//添加了自動創建目錄的功能
((File)file1).mkdir();
newfileName=System.currentTimeMillis()
+file.getFileName().substring(
file.getFileName().lastIndexOf('.'));
ByteArrayOutputStreambaos=newByteArrayOutputStream();
OutputStreambos=newFileOutputStream(filePath+"/"
+newfileName);
newpathname=filePath+"/"+newfileName;
System.out.println(newpathname);
//建立一個上傳文件的輸出流
System.out.println(filePath+"/"+file.getFileName());
intbytesRead=0;
byte[]buffer=newbyte[8192];
while((bytesRead=stream.read(buffer,0,8192))!=-1){
bos.write(buffer,0,bytesRead);//將文件寫入伺服器
}
bos.close();
stream.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
Ⅲ 怎麼用Java實現圖片上傳
下面這是servlet的內容:
package demo;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class DemoServlet extends HttpServlet {
private static final String UPLOAD_DIRECTORY = "upload";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setHeaderEncoding("UTF-8");
sfu.setProgressListener(new ProgressListener() {
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("文件大小為:"+pContentLength+",當前已處理:"+pBytesRead);
}
});
//判斷提交上來的數據是否是上傳表單的數據
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer= response.getWriter();
writer.println("Error:表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
factory.setSizeThreshold(MEMORY_THRESHOLD);
//設置臨時儲存目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//設置最大文件上傳值
sfu.setFileSizeMax(MAX_FILE_SIZE);
//設置最大請求值(包含文件和表單數據)
sfu.setSizeMax(MAX_REQUEST_SIZE);
String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;
File file=new File(uploadpath);
if(!file.exists()){
file.mkdir();
}
try {
List<FileItem> formItems = sfu.parseRequest(request);
if(formItems!=null&&formItems.size()>0){
for(FileItem item:formItems){
if(!item.isFormField()){
String fileName=new File(item.getName()).getName();
String filePath=uploadpath+File.separator+fileName;
File storeFile=new File(filePath);
System.out.println(filePath);
item.write(storeFile);
request.setAttribute("message", "文件上傳成功!");
}
}
}
} catch (Exception e) {
request.setAttribute("message", "錯誤信息:"+e.getMessage());
}
getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);
}
}
下面是jsp的內容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里轉發的路徑改一下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="demo.do" enctype="multipart/form-data" method="post">
<input type="file" name="file1" />
<%
String message = (String) request.getAttribute("message");
%>
<%=message%>
<input type="submit" value="提交"/>
</form>
</body>
</html>
這段代碼可以實現普通的文件上傳,有大小限制,上傳普通的圖片肯定沒問題,別的一些小的文件也能傳
Ⅳ 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可以上傳什麼格式的文件
理論上所有格式的文件都可以上傳!
Ⅵ java 上傳附件實現方法
上傳附件,實際上就是將文件存儲到遠程伺服器,進行臨時存儲。舉例:
**
* 上傳文件
*
* @param 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程序實現上傳文件到指定的URL地址
參考代碼如下:
import java.io.*;
/**
* 復制文件夾或文件夾
*/
public class CopyDirectory {
// 源文件夾
static String url1 = "f:/photos";
// 目標文件夾
static String url2 = "d:/tempPhotos";
public static void main(String args[]) throws IOException {
// 創建目標文件夾
(new File(url2)).mkdirs();
// 獲取源文件夾當前下的文件或目錄
File[] file = (new File(url1)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 復制文件
File(file[i],new File(url2+file[i].getName()));
}
if (file[i].isDirectory()) {
// 復制目錄
String sourceDir=url1+File.separator+file[i].getName();
String targetDir=url2+File.separator+file[i].getName();
Directiory(sourceDir, targetDir);
}
}
}
// 復制文件
public static void File(File sourceFile,File targetFile)
throws IOException{
// 新建文件輸入流並對它進行緩沖
FileInputStream input = new FileInputStream(sourceFile);
BufferedInputStream inBuff=new BufferedInputStream(input);
// 新建文件輸出流並對它進行緩沖
FileOutputStream output = new FileOutputStream(targetFile);
BufferedOutputStream outBuff=new BufferedOutputStream(output);
// 緩沖數組
byte[] b = new byte[1024 * 5];
int len;
while ((len =inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此緩沖的輸出流
outBuff.flush();
//關閉流
inBuff.close();
outBuff.close();
output.close();
input.close();
}
// 復制文件夾
public static void Directiory(String sourceDir, String targetDir)
throws IOException {
// 新建目標目錄
(new File(targetDir)).mkdirs();
// 獲取源文件夾當前下的文件或目錄
File[] file = (new File(sourceDir)).listFiles();
for (int i = 0; i < file.length; i++) {
if (file[i].isFile()) {
// 源文件
File sourceFile=file[i];
// 目標文件
File targetFile=new
File(new File(targetDir).getAbsolutePath()
+File.separator+file[i].getName());
File(sourceFile,targetFile);
}
if (file[i].isDirectory()) {
// 准備復制的源文件夾
String dir1=sourceDir + "/" + file[i].getName();
// 准備復制的目標文件夾
String dir2=targetDir + "/"+ file[i].getName();
Directiory(dir1, dir2);
}
}
}
}
Ⅷ 如何實現java 流式文件上傳
@Controller
public class UploadController extends BaseController {
private static final Log log = LogFactory.getLog(UploadController.class);
private UploadService uploadService;
private AuthService authService;
/**
* 大文件分成小文件塊上傳,一次傳遞一塊,最後一塊上傳成功後,將合並所有已經上傳的塊,保存到File Server
* 上相應的位置,並返回已經成功上傳的文件的詳細屬性. 當最後一塊上傳完畢,返回上傳成功的信息。此時用getFileList查詢該文件,
* 該文件的uploadStatus為2。client請自行處理該狀態下文件如何顯示。(for UPS Server)
*
*/
@RequestMapping("/core/v1/file/upload")
@ResponseBody
public Object upload(HttpServletResponse response,
@RequestParam(value = "client_id", required = false) String appkey,
@RequestParam(value = "sig", required = false) String appsig,
@RequestParam(value = "token", required = false) String token,
@RequestParam(value = "uuid", required = false) String uuid,
@RequestParam(value = "block", required = false) String blockIndex,
@RequestParam(value = "file", required = false) MultipartFile multipartFile,
@RequestParam Map<String, String> parameters) {
checkEmpty(appkey, BaseException.ERROR_CODE_16002);
checkEmpty(token, BaseException.ERROR_CODE_16007);
checkEmpty(uuid, BaseException.ERROR_CODE_20016);
checkEmpty(blockIndex, BaseException.ERROR_CODE_20006);
checkEmpty(appsig, BaseException.ERROR_CODE_10010);
if (multipartFile == null) {
throw new BaseException(BaseException.ERROR_CODE_20020);// 上傳文件不存在
}
Long uuidL = parseLong(uuid, BaseException.ERROR_CODE_20016);
Integer blockIndexI = parseInt(blockIndex, BaseException.ERROR_CODE_20006);
Map<String, Object> appMap = getAuthService().validateSigature(parameters);
AccessToken accessToken = CasUtil.checkAccessToken(token, appMap);
Long uid = accessToken.getUid();
String bucketUrl = accessToken.getBucketUrl();
// 從上傳目錄拷貝文件到工作目錄
String fileAbsulutePath = null;
try {
fileAbsulutePath = this.File(multipartFile.getInputStream(), multipartFile.getOriginalFilename());
} catch (IOException ioe) {
log.error(ioe.getMessage(), ioe);
throw new BaseException(BaseException.ERROR_CODE_20020);// 上傳文件不存在
}
File uploadedFile = new File(Global.UPLOAD_TEMP_DIR + fileAbsulutePath);
checkEmptyFile(uploadedFile);// file 非空驗證
Object rs = uploadService.upload(uuidL, blockIndexI, uid, uploadedFile, bucketUrl);
setHttpStatusOk(response);
return rs;
}
// TODO 查看下這里是否有問題
// 上傳文件非空驗證
private void checkEmptyFile(File file) {
if (file == null || file.getAbsolutePath() == null) {
throw new BaseException(BaseException.ERROR_CODE_20020);// 上傳文件不存在
}
}
/**
* 寫文件到本地文件夾
*
* @throws IOException
* 返回生成的文件名
*/
private String File(InputStream inputStream, String fileName) {
OutputStream outputStream = null;
String tempFileName = null;
int pointPosition = fileName.lastIndexOf(".");
if (pointPosition < 0) {// myvedio
tempFileName = UUID.randomUUID().toString();// 94d1d2e0-9aad-4dd8-a0f6-494b0099ff26
} else {// myvedio.flv
tempFileName = UUID.randomUUID() + fileName.substring(pointPosition);// 94d1d2e0-9aad-4dd8-a0f6-494b0099ff26.flv
}
try {
outputStream = new FileOutputStream(Global.UPLOAD_TEMP_DIR + tempFileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
return tempFileName;
} catch (IOException ioe) {
// log.error(ioe.getMessage(), ioe);
throw new BaseException(BaseException.ERROR_CODE_20020);// 上傳文件不存在
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
/**
* 測試此服務是否可用
*
* @param response
* @return
* @author zwq7978
*/
@RequestMapping("/core/v1/file/testServer")
@ResponseBody
public Object testServer(HttpServletResponse response) {
setHttpStatusOk(response);
return Global.SUCCESS_RESPONSE;
}
public UploadService getUploadService() {
return uploadService;
}
public void setUploadService(UploadService uploadService) {
this.uploadService = uploadService;
}
public void setAuthService(AuthService authService) {
this.authService = authService;
}
public AuthService getAuthService() {
return authService;
}
}
Ⅸ java實現文件的上傳和下載
用輸出流 接受 一個下載地址的網路流
然後將這個輸出流 保存到本地一個文件 後綴與下載地址的後綴相同··
上傳的話 將某個文件流 轉成位元組流 上傳到某個webservice方法里
-------要代碼來代碼
URL url=new URL("http://www..com/1.rar");
URLConnection uc=url.openConnection();
InputStream in=uc.getInputStream();
BufferedInputStream bis=new BufferedInputStream(in);
FileOutputStream ft=new FileOutputStream("E://1.rar");
這是下載 上傳太麻煩就不給寫了