導航:首頁 > IDC知識 > java文件上傳至伺服器

java文件上傳至伺服器

發布時間:2020-12-29 23:23:31

1、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();

}

2、java web怎麼實現文件上傳到伺服器

/**
* 上傳到本地
* @param uploadFile
* @param request
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public Map<String, Object> uploadApkFile(@RequestParam("uploadUpdateHistoryName") MultipartFile uploadFile,
HttpServletRequest request) {
Map<String, Object> map = new HashMap<>();
// 上傳文件校驗,包括上傳文件是否為空、文件名稱是否為空、文件格式是否為APK。
if (uploadFile == null) {
map.put("error", 1);
map.put("msg", "上傳文件不能為空");
return map;
}
String originalFilename = uploadFile.getOriginalFilename();
if (StringUtils.isEmpty(originalFilename)) {
map.put("error", 1);
map.put("msg", "上傳文件名稱不能為空");
return map;
}
String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
if (extName.toUpperCase().indexOf("APK") < 0) {
map.put("error", 1);
map.put("msg", "上傳文件格式必須為APK");
return map;
}

String path = request.getSession().getServletContext().getRealPath("upload");
String fileName = uploadFile.getOriginalFilename();
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 保存
String downLoadUrl = null;
try {
uploadFile.transferTo(targetFile);
downLoadUrl = request.getContextPath() + "/upload/" + fileName;
map.put("error", 0);
map.put("downLoadUrl", downLoadUrl);
map.put("msg", "上傳文件成功");
return map;
} catch (Exception e) {
e.printStackTrace();
map.put("error", 1);
map.put("msg", "上傳文件失敗");
return map;
}
}

//上傳文件
$('#btnUpload').bind('click',function(){
// var formdata= $('#uploadForm').serializeJSON();
var formdata = new FormData($( "#uploadForm" )[0]);
$.ajax({
url:"upload.do",
data:formdata,
async: false,
cache: false,
processData:false,
contentType:false,
// dataType:'json',
type:'post',
success:function(value){
if(value.error==0){
$('#downLoadUrlId').val(value.downLoadUrl);
$.messager.alert('提示',value.msg);
$('#uploadWindow').window('close');
}else{
$.messager.alert('提示',value.msg);
}
}
});
});

<div id="uploadWindow" class="easyui-window" title="apk上傳"
style="width: 230px;height: 100px" data-options="closed:true">
<form id="uploadForm" enctype="multipart/form-data">
<td><input type ="file" style="width:200px;" name = "uploadUpdateHistoryName"></td>
</form>
<button id="btnUpload" type="button">上傳Apk</button>
</div>

java js html

3、java後台文件上傳到資源伺服器上

package com.letv.dir.cloud.util;import com.letv.dir.cloud.controller.DirectorWatermarkController;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by xijunge on 2016/11/24 0024. */public class HttpRequesterFile { private static final Logger log = LoggerFactory.getLogger(HttpRequesterFile.class); private static final String TAG = "uploadFile"; private static final int TIME_OUT = 100 * 1000; // 超時時間 private static final String CHARSET = "utf-8"; // 設置編碼 /** * 上傳文件到伺服器 * * @param file * 需要上傳的文件 * @param RequestURL * 文件伺服器的rul * @return 返回響應的內容 * */ public static String uploadFile(File file, String RequestURL) throws IOException {
String result = null;
String BOUNDARY = "letv"; // 邊界標識 隨機生成 String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 內容類型 try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允許輸入流 conn.setDoOutput(true); // 允許輸出流 conn.setUseCaches(false); // 不允許使用緩存 conn.setRequestMethod("POST"); // 請求方式 conn.setRequestProperty("Charset", CHARSET); // 設置編碼 conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

4、java 實現文件上傳到另一台伺服器,該怎麼解決

上傳本地文件代碼
使用步驟如下:
1.調用AddFile函數添加本地文件,注意路徑需要使用版雙斜框(\\)
2.調用PostFirst函數開始上權傳文件。
JavaScript code?<script type="text/javascript" language="javascript"> var fileMgr = new HttpUploaderMgr(); fileMgr.Load();//載入控制項 window.onload = function() { fileMgr.Init();//初始化控制項 //添加一個本地文件 fileMgr.AddFile("D:\\Soft\\QQ2010.exe"); fileMgr.PostFirst(); };</script>

5、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.copyFile(upload[i], target);
//這是一個文件復制類copyFile()裡面就是IO操作,如果你不用這個類也可以自己寫一個IO復制文件的類
}

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

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

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

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

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

實現思路
通過自定義函數實現文件上傳到指定路徑,然後通過在按鈕的自定義事件(填報自定義事件)中將數據提交入庫並調用此自定義函數即可。

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

UI端:
1.使磁碟的目錄結構在界面上以樹形結構展現
2.上傳表單包含1中的磁碟目錄樹(普遍專為下拉屬樹),當用戶上傳文件前可以指定上傳目錄
服務端:
1.遍歷所在伺服器磁碟,或通過遠程調用遍歷其他伺服器磁碟
2.處理UI端表單提交數據

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

實現思路 通過自定義函數實現文件上傳到指定路徑,然後通過在按鈕的自定義事件(填報自定義事件)中將數據提交入庫並調用此自定義函數即可。

9、JAVA如何把本地文件上傳到伺服器。

這個你就要參考,java上傳文件的相關資料了。
告訴你有現成的代碼,你可以找寫拷貝過去直接使用。

與java文件上傳至伺服器相關的知識