標籤:處理 form string input 資源檔 lte 儲存 rac odi
Spirng檔案上傳
定義配置System.properties檔案的檔案上傳路徑
fileSaveDir=E:/ceshi/
<!--SpringMVC配置-->
<!--讀取檔案上傳資源檔-->
<context:property-placeholder location="classpath:system.properties"/>
SpringMVC檔案上傳<!-- 多部分檔案上傳 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上傳檔案的大小,單位為位元組 -->
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<!-- 請求的編碼格式 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 上傳檔案的臨時路徑 -->
<property name="uploadTempDir" value="fileUpload/temp"></property>
</bean>
1.頁面部分
<body>
<form action="/Update" method="post" enctype="multipart/form-data">
<center>
<h2>檔案上傳</h2>
使用者姓名:<input name="username"/><br/>
帳戶圖片:<input type="file" name="userhead"><br/>
帳戶圖片:<input type="file" name="userhead"><br/>
帳戶圖片:<input type="file" name="userhead"><br/>
<input type="submit" value="提交"/>
</center>
</form>
</body>
3.檔案上傳控制器
@Controller
public class UpdateController {
private Logger logger = LogManager.getLogger(UpdateController.class);
//擷取資源檔下的定義的地址
@Value("${fileSaveDir}")
private String fileSaveDir;
@RequestMapping("/Update")
public String upfile(String username, MultipartFile[] userhead ){
logger.debug("這是fileSaceDir"+fileSaveDir);
for (MultipartFile file:userhead) {
logger.debug("username是"+username+"userhead是"+userhead);
//自動產生動態碼
String filename=UUID.randomUUID().toString();
logger.debug("uuid是"+filename);
//存入Map集合中
Const.fileMap.put(filename,file.getOriginalFilename());
try {
file.transferTo(new File(fileSaveDir+file.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
}
return "succ";
}
設定檔案上傳名稱
public class Const {
public static Map<String,String> fileMap = new HashMap<String, String>();
//類比資料庫儲存如map中
static {
fileMap.put("6dc0d57c-1ee2-4a35-8e95-817d02ad5667","1.jpg");
fileMap.put("b8d74873-797d-458d-93dd-14fe3122bb55","2.jpg");
fileMap.put("c4cf5385-cb4a-48a8-a763-b9957ffbb807","3.jpg");
檔案的下載
/擷取資源檔下的定義的地址
@Value("${fileSaveDir}")
private String saveDir;
@RequestMapping("/downFile")
public void downFile(String filename, HttpServletResponse resp) throws IOException {
resp.setContentType("application/octet-stream; charset=utf-8");
// 處理中文檔案名稱中文亂碼問題
String realOriginalFilename = Const.fileMap.get(filename);
String name = new String(realOriginalFilename.getBytes("utf-8"), "ISO-8859-1");
resp.setHeader("Content-Disposition", "attachment; filename=" + name);
IOUtils.copy(new FileInputStream(new File(saveDir, filename)), resp.getOutputStream());
SpirngMVC檔案上傳