Android檔案上傳攜帶引數及伺服器SSM程式碼
一 Android端程式碼
package com.xky.recall.network; import com.xky.recall.utils.LogUtils; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder;import java.util.UUID; /** * @author weijinsong * @date 2018/6/4. */ public class UploadUtils { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10 * 1000;//超時時間 private static final String CHARSET = "utf-8";//設定編碼 /** * android上傳檔案到伺服器 * * @param file需要上傳的檔案 * @param url 請求的url * @return 返回響應的內容 */ public static String uploadImage(URL url, File file, String userId, String userAccount, String albumName) { String result = "error"; String BOUNDARY = UUID.randomUUID().toString();//邊界標識 隨機生成 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); conn.connect(); if (file.exists()) { //當檔案不為空,把檔案包裝並且上傳 DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); /** * set user account */ dos.writeBytes(PREFIX + BOUNDARY + LINE_END); dos.writeBytes("Content-Disposition: form-data; " + "name=\"userId\"" + LINE_END); dos.writeBytes(LINE_END); dos.writeBytes( URLEncoder.encode(userId,"utf-8") + LINE_END); /** * set user account */ dos.writeBytes(PREFIX + BOUNDARY + LINE_END); dos.writeBytes("Content-Disposition: form-data; " + "name=\"userAccount\"" + LINE_END); dos.writeBytes(LINE_END); dos.writeBytes( URLEncoder.encode(userAccount,"utf-8") + LINE_END); /** * set album name */ dos.writeBytes(PREFIX + BOUNDARY + LINE_END); dos.writeBytes("Content-Disposition: form-data; " + "name=\"albumName\"" + LINE_END); dos.writeBytes(LINE_END); dos.writeBytes( URLEncoder.encode(albumName,"utf-8") + LINE_END); dos.writeBytes(PREFIX + BOUNDARY + LINE_END); dos.writeBytes("Content-Disposition: form-data; " + "name=\"recall\";filename=\"" + file.getName() + "\"" + LINE_END); dos.writeBytes(LINE_END); FileInputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = -1; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); dos.write(end_data); dos.flush(); /* * 獲取響應碼 200=成功 * 當響應成功,獲取響應的流 */ int res = conn.getResponseCode(); if (res == HttpURLConnection.HTTP_OK) { InputStream input = conn.getInputStream(); StringBuilder sbs = new StringBuilder(); int ss; while ((ss = input.read()) != -1) { sbs.append((char) ss); } result = sbs.toString(); } } } catch (IOException e) { e.printStackTrace(); } return result; } private static String getMIMEType(File file) { String fileName = file.getName(); if (fileName.endsWith("png") || fileName.endsWith("PNG")) { return "image/png"; } else { return "image/jpg"; } } }
二 伺服器SSM程式碼
/**
* @function 檔案上傳//// , @RequestParam("file") MultipartFile file
* @param user
* @param file
* @param request
* @return
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public void uploadFile(User user, HttpServletRequest request,
HttpSession session, HttpServletResponse response) {
MultipartHttpServletRequest rq = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> file_list = rq.getFileMap();
String pictureName = null;
String userId = rq.getParameter("userId").toString();
String userAccount = rq.getParameter("userAccount").toString();
String albumName = rq.getParameter("albumName").toString();
boolean isStorePicture = false;
try{
//System.out.println(URLDecoder.decode(userAccount, "utf-8").toString());
userId = URLDecoder.decode(userId, "utf-8");
userAccount = URLDecoder.decode(userAccount, "utf-8");
albumName = URLDecoder.decode(albumName, "utf-8");
} catch(Exception e) {
e.printStackTrace();
}
Album album = new Album();
album.setUserId(Integer.parseInt(userId));
album.setAlbumName(albumName);
Picture picture = new Picture();
if (file_list != null && file_list.size() > 0) {
if (file_list.containsKey("recall")) {
MultipartFile file = file_list.get("recall");
if (!file.isEmpty()) {
if((album = albumService.findAlbumByAlbumNameAndUserId(album)) != null) {
picture.setAlbumId(album.getAlbumId());
pictureName = file.getName();
System.out.println(pictureName);
pictureName = file.getOriginalFilename();
picture.setPictureName(pictureName);
if(pictureService.findPictureByAlbumIdAndPictureName(picture) == null) {
isStorePicture = true;
}
}
if(isStorePicture) {
/*
* 在開發過程中,一般不會把檔案路徑寫死在某個盤的某個路徑下面 1.通過ul無法訪問檔案
* 2.無法匹配各個環境(開發環境、測試環境、線上運營環境)路徑需求 windows/Linux 解決辦法:
* 將檔案儲存到工程路徑下面
*/
String path = request.getSession().getServletContext()
.getRealPath("/")
+ "upload/" ;
System.out.println("path = " + path);
// 判斷目錄是否存在,不存在則建立目錄
File pFile = new File(path);
if (!pFile.exists()) {
pFile.mkdir();
}
/**
* create userAccount file
*/
path += userAccount + "/";
File userAccountFile = new File(path);
if(!userAccountFile.exists()) {
userAccountFile.mkdir();
}
/**
* create userAccount albumName file
*/
path += albumName + "/";
File albumNameFile = new File(path);
if(!albumNameFile.exists()) {
albumNameFile.mkdir();
}
String fileName = file.getOriginalFilename();
String userAvatarPath = null;
String ext = fileName.substring(fileName.lastIndexOf("."));
/*
* java隨機id UUID.randomUUID() 但是儲存到服務的檔名字找不到 解決辦法:方法1:
* 在實際開發過程中,會單獨的建一張檔案上傳表,儲存檔案的id、名字、url、大小、字尾名, 其他業務表儲存檔案的id
* 方法2:
* 直接在業務表裡面寫入檔案的真實名稱file.getOriginalFilename()和檔案的儲存位置(url
* )filePath
*
* 但是在實際開發中,把所有檔案都上傳到web目錄下面是不可取的,因為web服務太大會影響啟動,同時web又大小限制
* 實際開發中,web服務值儲存一些關鍵同時比較小的檔案(比如頭像、app下載包),
* 其他檔案上傳到本地之後,我們會將檔案上傳到檔案伺服器
* (如fastdfs、ftp等),然後將上傳後的地址儲存在資料庫同時刪除本地檔案
*/
userAvatarPath = UUID.randomUUID() + ext;
//String filePath = path + userAvatarPath;
String filePath = path + fileName;
picture.setPicturePath(userAccount + "/" + albumName + "/" + fileName);
picture.setPictureCreateDate(new Date(System.currentTimeMillis()));
picture.setPictureModifyDate(new Date(System.currentTimeMillis()));
/*
* user.setUserPortraitPath(userAvatarPath);
* user.setUserCreateDate(new
* Date(System.currentTimeMillis()));
* user.setUserModifyDate(new
* Date(System.currentTimeMillis()));
*/
try {
pictureService.addPicture(picture);
file.transferTo(new File(filePath));
session.setAttribute("newfilename", userAvatarPath);
// userService.addUser(user);
} catch (IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//return "/userLogin";// redirect:/user/index
}
三 spring-mvc配置檔案加入
<!-- 檔案上傳配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
<property name="maxUploadSize">
<value>524288000</value><!-- 上傳檔案大小限制為500M,31*1024*1024 -->
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>