上传图片总是出现空指针错误
jsp 文件中的form表单
<form name="form1" method="post" action="Uinfor_UploadPicture.action" id="form1" enctype="multipart/form-data">
<div class="right">
<!--Step 1-->
<div id="Step1Container">
<div class="title"><b>更换照片</b></div>
<div id="uploadcontainer">
<div class="uploadtooltip">请选择新的照片文件,文件需小于2.5MB</div>
<div class="uploaddiv"><input type="file" name="myFile" id="fuPhoto" title="选择照片" /></div>
<div class="uploaddiv"><input type="submit" name="btnUpload" value="上 传" id="btnUpload" /></div>
</div>
</div>
</div>
</form>
action 文件:
try{
imageFileName = new Date().getTime() +
fileUpload.getExtention(fileName); //310
File imageFile = new File(ServletActionContext.getServletContext().getRealPath("text/UploadPhoto")
+"/"+imageFileName);
fileUpload.copy(myFile,imageFile);
}catch(Exception e){
e.printStackTrace();
}
FileUpload 类:::
package thinksns.tool;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUpload {
private static final int BUFFER_SIZE = 16 * 1024;
public void copy(File src,File dst){
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),
BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} finally {
if(null!=in){
in.close();
}
if(null!=out){
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getExtention(String fileName){
int pos = fileName.lastIndexOf("."); //43
return fileName.substring(pos);
}
}
报错:;
java.lang.NullPointerException
at thinksns.tool.FileUpload.getExtention(FileUpload.java:43)
at thinksns.action.UinforAction.UploadPicture(UinforAction.java:310)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
感觉没写错啊,就是报空指针错
[解决办法]
<input type="file" name="myFile" id="fuPhoto" title="选择照片" />你上传的文件name为myFile那么你
将 private String fileName; 改为myFileFileName