Java 上传文件

Java 上传文件:

<!DOCTYPE html>
<html>
<head>
<meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
<meta name="description" content="this is my page"></meta>
<meta name="content-type" content="text/html; charset=UTF-8"></meta>
<title>图片上传</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/testUploadimg"> 
图片:
<!--在input中设置属性multiple=“multiple”,既可以上传多个文件-->
<input type="file" id="mf" name="file"/><br/>  
<input type="submit" value="上传" />
<input type="submit" id="sub_btn" value="上传2" />
</form>
</body>
    <script>
    //ajax方式上传文件
        $(function () {
            $("#sub_btn").click(function () {
                var formData=new FormData();
                formData.append("file",$("#mf")[0]);
                $.ajax({
                    type:"post",
                    url:"testUploadimg",
                    dataType:"json",
                    data:formData,
                    //是否缓存
                    cache: false,
              		//当设置为false的时候,jquery 的ajax 提交的时候会序列化 data
                    processData: false,
                    /*contentType都是默认的值:application/x-www-form-urlencoded;
                     *表单中设置的contentType为"multipart/form-data";
                     * ajax 中 contentType 设置为 false ,是为了避免 JQuery对要提交
                     * 的表单中的enctype值修改*/
                    contentType: false,
                    success:function (result) {
                    
                    }
                })
            })
        })
    </script>
</html>
@Controller
public class UploadController {  
//跳转到上传文件的页面  
@RequestMapping(value = "/gouploadimg", method = RequestMethod.GET)  
public String goUploadImg() {    
	//跳转到 templates 目录下的 uploadimg.html    
	return "uploadimg";  
}  

//处理文件上传  
@ResponseBody //返回json数据  
@RequestMapping(value = "/testUploadimg", method = RequestMethod.POST)  
public String uploadImg(@RequestPart("file") MultipartFile file) {
	//多个文件用MultipartFile[] file接收
	String contentType = file.getContentType();    
	String fileName = file.getOriginalFilename();    
	String filePath = "D:/img";    
	if (file.isEmpty()) {
		return "文件为空!";
	}      
	try {      
		uploadFile(file.getBytes(), filePath, fileName);    
	} catch (Exception e) {      
		// TODO: handle exception    
	}    
	//返回json    
	return "上传成功";  
}  
 
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {    
	File targetFile = new File(filePath);    
	if (!targetFile.exists()) {      
		targetFile.mkdirs();    
 	}    
	FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);    
	out.write(file);    
	out.flush();    
	out.close();  
	}
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值