Struts2 使用Jquery+ajax 文件上传
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Struts2 使用Jquery+ajax 文件上传,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2600字,纯文字阅读大概需要4分钟。
内容图文
话不多说 直接上代码
前台js:
1 var formData = new FormData(); 2 formData.append("file1",$("#file1")[0].files[0]);//第一个file1代表后台文件属性名,第二个file1表示html中input的id 3$.ajax({ 4 type:"post", 5 url:"ajax/uploadFile", 6 data:formData, 7 processData : false, 8 contentType : false, 9 success : function(res) { 10 console.log(res); 11if(res=="success"){ 12 $("#labResult").text("文件上传成功"); 13 } 14 }, 15 error : function(msg) { 16 console.log(msg.responsText); 17 } 18 });
后台java:
1 import java.io.File; 2 import java.io.FileInputStream; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 import org.apache.struts2.ServletActionContext; 12 13 import com.opensymphony.xwork2.ActionContext; 14 import com.opensymphony.xwork2.ActionSupport; 15 16 public class UploadAction extends ActionSupport{ 17private File file1 ; 18private String file1FileName ;//FileName为固定写法19public File getFile1() { 20return file1; 21 } 22publicvoid setFile1(File file1) { 23this.file1 = file1; 24 } 25public String getFile1FileName() { 26return file1FileName; 27 } 28publicvoid setFile1FileName(String file1FileName) { 29this.file1FileName = file1FileName; 30 } 31public String uploadFile() throws Exception { 3233 String path = ServletActionContext.getRequest().getServletContext().getRealPath("/WEB-INF/upload"); 34//查看是否存在目录 不存在则创建35 File file = new File(path); 36//如果目录不存在37if(!file.exists()){ 38 file.mkdirs(); 39 } 40//文件不为空 则上传41if(file1!=null){ 42//输出流 43 OutputStream os = new FileOutputStream(new File(path,file1FileName)); 44//输入流 45 InputStream is = new FileInputStream(file1); 4647byte[] buf = newbyte[1024]; 48int length = 0 ; 4950while(-1 != (length = is.read(buf) ) ) 51 { 52 os.write(buf, 0, length) ; 53 } 54 is.close(); 55 os.close(); 56 } 57return "success"; 58 } 5960publicvoid uploadFile(){ 61 System.out.println("file1:"+file1+"."); 62 System.out.println("file1FileName:"+file1FileName+"."); 63 String path=""; 64try { 65 path=uploadFile(); 66 HttpServletResponse response = ServletActionContext.getResponse(); 67 response.setContentType("text/html;charset=utf-8"); 68 response.getWriter().write(path); 69 } catch (Exception e) { 70 e.printStackTrace(); 71 } 72 } 73 }
struts:
< package name ="ajax" extends ="json-default" namespace ="/ajax" > < action name ="uploadFile" class ="包名.UploadAction" method ="uploadFile" ></ action > </ package >
有啥不懂,底下留言。
原文:http://www.cnblogs.com/jinghun/p/7535041.html
内容总结
以上是互联网集市为您收集整理的Struts2 使用Jquery+ajax 文件上传全部内容,希望文章能够帮你解决Struts2 使用Jquery+ajax 文件上传所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。