现在企业很少用传统的方法去上传图片,显示图片,一般都会转成字节数据数组或是base64来处理,
以下介绍如何将页面的file在后台转成字节数组来处理,
controller类代码
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@RequestMapping(value="/upJpg")
public ModelAndView upJpg(MultipartHttpServletRequest request) throws Exception{
List<MultipartFile> list = request.getFiles("file");
MultipartFile file = list.get(0);
CommonsMultipartFile commonsMultipartFile =(CommonsMultipartFile) file;
FileItem item = commonsMultipartFile.getFileItem();
String fileName = item.getName();
String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
byte[] filebyte = IOUtils.toByteArray(request.getFile("file").getInputStream());
return null;
}
以下提供一个方法可以把前端的参数转成map:
public Map tranfMap(MultipartHttpServletRequest request){
Map properties = request.getParameterMap();
Map returnMap = new HashMap();
Iterator entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
value = value.substring(0, value.length()-1);
}else if(valueObj instanceof String){
value = valueObj.toString();
}else {
value = valueObj.toString();
}
returnMap.put(name, value);
}
map = returnMap;
}
jsp页面
<form action="recharge_record/upJpg.do" name="Form" id="Form" method="post" enctype="multipart/form-data">
<p>图片:</p>
<p><input type="file" name="file" id="file" maxlength="32" /></p>
<p><input type="submit" name="submit" id="submit" value="上传" maxlength="32" /></td></p>
</form>