enctype="multipart/form-data"表单传值问题
知识点:
一、application/x-www-form-urlencoded:
1、表单中的enctype值如果不设置,则默认是application/x-www-form-urlencoded,它会将表单中的数据变为键值对
的形式
2、如果action为get,则将表单数据编码为(name1=value1&name2=value2…),然后把这个字符串加到url后面,中间
用?分隔
3、如果action为post,浏览器把form数据封装到http body中,然后发送到服务器。
二、text/plain:
表单以纯文本形式进行编码
三、multipart/form-data:
1、当我们上传的含有非文本内容,即含有文件(txt、MP3等)的时候,需要将form的enctype设置为multipart/form-
data。
2、将表单中的数据变成二进制数据进行上传,所以这时候这时如果用request是无法直接获取到相应表单的值的
/**
* 附件上传
* @param
* @return
*/
@ResponseBody
@RequestMapping("/fileUpload")
public Response fileUpload(@RequestParam("file") MultipartFile[] myfile) {
Map<String, Object> paramMap = new HashMap<String, Object>();
Response response = new Response();
//当前日期
Date date = new Date();
String path1= PropertyConfigure.getProperty("IMG_PATH").toString();
//格式化并转换String类型
String imgPath= new SimpleDateFormat("yyyy/MM/dd").format(date) +"/";
String path= path1 + imgPath;
//创建文件夹
File f = new File(path);
if(!f.exists()){
f.mkdirs();
}
try {
int len = myfile.length;
for (int i = 0; i < len; i++) {
MultipartFile file = myfile[i];
if (file.isEmpty()) {
// return;
} else {
file.transferTo(new File( path + file.getOriginalFilename()));
paramMap.put("file_path", imgPath + file.getOriginalFilename());
}
}
} catch (IOException e) {
e.printStackTrace();
}
String file_id = UUID.randomUUID().toString();
paramMap.put("file_id", file_id);
appApiService.saveImg(paramMap);
return response.success(file_id);
}
/**
* 附件删除
* @param paramMap
* @param
* @return
*/
@ResponseBody
@RequestMapping("/fileDelete")
public Response fileDelete(@RequestParam Map<String, Object> paramMap) {
Response response = new Response();
if (paramMap.size() == 0 || paramMap.get("file_id") == null)
{
response.failure("无法删除文件");
return response;
}
int delete = appApiService.fileDelete(paramMap);
response.success(delete);
return response;
}
@RequestMapping("/downImg")
public String downIo(@RequestParam Map<String, Object> paramMap,HttpServletResponse response) throws IOException {
ServletOutputStream out = null;
FileInputStream ips = null;
try {
//获取图片存放路径
List<Map<String, Object>> list = appApiService.fileList(paramMap);
String name = list.get(0).get("file_path").toString();
String imgPath= PropertyConfigure.getProperty("IMG_PATH").toString() + name;
ips = new FileInputStream(new File(imgPath));
String filename;
if(paramMap.get("file_name")!= null){
filename = paramMap.get("file_name").toString();
}else {
filename = "img";
}
/*String filename = paramMap.get("file_name").toString();*/
filename = URLEncoder.encode(filename,"UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
response.setContentType("multipart/form-data");
out = response.getOutputStream();
//读取文件流
int len = 0;
byte[] buffer = new byte[1024 * 10];
while ((len = ips.read(buffer)) != -1){
out.write(buffer,0,len);
}
out.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
out.close();
ips.close();
}
return null;
}