java实现上传图片(java实现上传图片到APP端)

华为云服务器特价优惠火热进行中!

2核2G2兆仅需 38 元;4核4G3兆仅需 79 元。购买时间越长越优惠!更多配置及优惠价格请咨询客服。

合作流程:
1、点击链接注册/关联华为云账号:点击跳转
2、添加客服微信号:cloud7591,确定产品方案、价格方案、服务支持方案等;
3、客服协助购买,并拉微信技术服务群,享受一对一免费技术支持服务;
技术专家在金蝶、华为、腾讯原厂有多年工作经验,并已从事云计算服务8年,可对域名、备案、网站搭建、系统部署、AI人工智能、云资源规划等上云常见问题提供更专业靠谱的服务,对相应产品提供更优惠的报价和方案,欢迎咨询。

本篇文章给大家谈谈java实现上传图片,以及java实现上传图片到APP端对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

微信号:cloud7591
如需了解更多,欢迎添加客服微信咨询。
复制微信号

本文目录一览:

Java怎么实现上传图片的等比缩放,原文件和缩放的文件都要上传到服务器

/**

     * 等比例缩放图片

     * @param infile

     * @param outfile

     * @param width

     * @param height

     * @param quality

     * @throws IOException

     * @throws InterruptedException

     */

    public static void Thumbnail(String infile, String outfile, int width, int height, int quality) throws IOException, InterruptedException {

        // save thumbnail image to OUTFILE

        //System.out.println("infile:" + infile);

        BufferedImage thumbImage = null;

        BufferedOutputStream out = null;

        Image image = null;

        image = Toolkit.getDefaultToolkit().createImage(infile);

        MediaTracker mediaTracker = new MediaTracker(new Container());

        mediaTracker.addImage(image, 0);

        mediaTracker.waitForID(0);

        int thumbWidth = width;

        int thumbHeight = height;

        double thumbRatio = (double) thumbWidth / (double) thumbHeight;

        int imageWidth = image.getWidth(null);

        int imageHeight = image.getHeight(null);

        double imageRatio = (double) imageWidth / (double) imageHeight;

        if (thumbRatio  imageRatio) {

            thumbHeight = (int) (thumbWidth / imageRatio);

        } else {

            thumbWidth = (int) (thumbHeight * imageRatio);

        }

        thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);

        Graphics2D graphics2D = thumbImage.createGraphics();

        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

        graphics2D.drawImage(image,0,0, thumbWidth, thumbHeight, null);

        out = new BufferedOutputStream(new FileOutputStream(outfile));

        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);

        quality = Math.max(0, Math.min(quality, 100));

        param.setQuality((float) quality / 100.0f, false);

        encoder.setJPEGEncodeParam(param);

        encoder.encode(thumbImage);

        out.close();

        thumbImage = null;

        out = null;

        image = null;

    }

原文转载自:

java实现图片上传至服务器并显示,如何做?希望要具体的代码实现

很简单。

可以手写IO读写(有点麻烦)。

怕麻烦的话使用FileUpload组件 在servlet里doPost嵌入一下代码

public void doPost(HttpServletRequest request,HttpServletResponse response)

throws ServletException,IOException{

response.setContentType("text/html;charset=gb2312");

PrintWriter out=response.getWriter();

//设置保存上传文件的目录

String uploadDir =getServletContext().getRealPath("/up");

System.out.println(uploadDir);

if (uploadDir == null)

{

out.println("无法访问存储目录!");

return;

}

//根据路径创建一个文件

File fUploadDir = new File(uploadDir);

if(!fUploadDir.exists()){

if(!fUploadDir.mkdir())//如果UP目录不存在 创建一个 不能创建输出...

{

out.println("无法创建存储目录!");

return;

}

}

if (!DiskFileUpload.isMultipartContent(request))

{

out.println("只能处理multipart/form-data类型的数据!");

return ;

}

DiskFileUpload fu = new DiskFileUpload();

//最多上传200M数据

fu.setSizeMax(1024 * 1024 * 200);

//超过1M的字段数据采用临时文件缓存

fu.setSizeThreshold(1024 * 1024);

//采用默认的临时文件存储位置

//fu.setRepositoryPath(...);

//设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码

fu.setHeaderEncoding("gb2312");

//得到所有表单字段对象的集合

List fileItems = null;

try

{

fileItems = fu.parseRequest(request);//解析request对象中上传的文件

}

catch (FileUploadException e)

{

out.println("解析数据时出现如下问题:");

e.printStackTrace(out);

return;

}

//处理每个表单字段

Iterator i = fileItems.iterator();

while (i.hasNext())

{

FileItem fi = (FileItem) i.next();

if (fi.isFormField()){

String content = fi.getString("GB2312");

String fieldName = fi.getFieldName();

request.setAttribute(fieldName,content);

}else{

try

{

String pathSrc = fi.getName();

if(pathSrc.trim().equals("")){

continue;

}

int start = pathSrc.lastIndexOf('\\');

String fileName = pathSrc.substring(start + 1);

File pathDest = new File(uploadDir, fileName);

fi.write(pathDest);

String fieldName = fi.getFieldName();

request.setAttribute(fieldName, fileName);

}catch (Exception e){

out.println("存储文件时出现如下问题:");

e.printStackTrace(out);

return;

}

finally //总是立即删除保存表单字段内容的临时文件

{

fi.delete();

}

}

}

注意 JSP页面的form要加enctype="multipart/form-data" 属性, 提交的时候要向服务器说明一下 此页面包含文件。

如果 还是麻烦,干脆使用Struts 的上传组件 他对FileUpload又做了封装,使用起来更傻瓜化,很容易掌握。

-----------------------------

以上回答,如有不明白可以联系我。

java 中如何向服务器上传图片

我们使用一些已有的组件帮助我们实现这种上传功能。

常用的上传组件:

Apache 的 Commons FileUpload

JavaZoom的UploadBean

jspSmartUpload

以下,以FileUpload为例讲解

1、在jsp端

form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data"

要注意enctype="multipart/form-data"

然后只需要放置一个file控件,并执行submit操作即可

input name="file" type="file" size="20"

input type="submit" name="submit" value="提交"

2、web端

核心代码如下:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

try {

List items = upload.parseRequest(request);

Iterator itr = items.iterator();

while (itr.hasNext()) {

FileItem item = (FileItem) itr.next();

if (item.isFormField()) {

System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));

} else {

if (item.getName() != null !item.getName().equals("")) {

System.out.println("上传文件的大小:" + item.getSize());

System.out.println("上传文件的类型:" + item.getContentType());

System.out.println("上传文件的名称:" + item.getName());

File tempFile = new File(item.getName());

File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());

item.write(file);

request.setAttribute("upload.message", "上传文件成功!");

}else{

request.setAttribute("upload.message", "没有选择上传文件!");

}

}

}

}catch(FileUploadException e){

e.printStackTrace();

} catch (Exception e) {

e.printStackTrace();

request.setAttribute("upload.message", "上传文件失败!");

}

request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);

}

java web开发,上传图片并读取

java web开发中,使用文件操作类来上传图片并读取,如下代码:

 * @desc: 图片处理工具

 * @author: bingye

 * @createTime: 2015-3-17 下午04:25:32

 * @version: v1.0

 */

public class ImageUtil {

 

    /**

    * 将图片写到客户端

    * @author: bingye

    * @createTime: 2015-3-17 下午04:36:04

    * @history:

    * @param image

    * @param response void

    */

    public static void writeImage(byte[] image,HttpServletResponse response){

        if(image==null){

            return;

        }

        byte[] buffer=new byte[1024];

        InputStream is=null;

        OutputStream os=null;

        try {

            is=new ByteArrayInputStream(image);

            os=response.getOutputStream();

            while(is.read(buffer)!=-1){

                os.write(buffer);

                os.flush();

            }

        } catch (IOException e) {

            e.printStackTrace();

        } finally{

            try {

                if(is!=null){is.close();}

                if(os!=null){os.close();}

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }

     

    /**

    * 获取指定路劲图片

    * @author: bingye

    * @createTime: 2015-3-21 上午10:50:44

    * @param filePath

    * @param response void

    */

    public static void writeImage(String filePath,HttpServletResponse response){

        File imageFile=new File(filePath); 

        if(imageFile!=null  imageFile.exists()){

            byte[] buffer=new byte[1024];

            InputStream is=null;

            OutputStream os=null;

            try {

                is=new FileInputStream(imageFile);

                os=response.getOutputStream();

                while(is.read(buffer)!=-1){

                    os.write(buffer);

                    os.flush();

                }

            } catch (FileNotFoundException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            } finally{

                try {

                    if(is!=null){is.close();}

                    if(os!=null){os.close();}

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

     

    /**

    * 图片上传到文件夹

    * @author: bingye

    * @createTime: 2015-3-20 下午08:07:25

    * @param file

    * @param savePath

    * @return boolean

    */

    public static ResultDto uploadToLocal(CommonsMultipartFile file,String savePath){

        if(file!=null  !file.isEmpty()){

            //获取文件名称

            String fileName=file.getOriginalFilename();

            //获取后缀名

            String suffixName=fileName.substring(fileName.indexOf(".")+1);

            //新名称

            String newFileName=System.currentTimeMillis()+"."+suffixName;

            //新文件路劲

            String filePath=savePath+newFileName;

            //获取存储文件路径

            File fileDir=new File(savePath);

            if(!fileDir.exists()){

                //如果文件夹没有:新建

                fileDir.mkdirs();

            }

            FileOutputStream fos=null;

            try {

                fos=new FileOutputStream(filePath);

                fos.write(file.getBytes());

                fos.flush();

                return ResultUtil.success("UPLOAD_SUCCESS", URLEncoder.encode(newFileName,"utf-8"));

            } catch (Exception e) {

                e.printStackTrace();

                return ResultUtil.fail("UPLOAD_ERROR");

            } finally{

                try {

                    if(fos!=null){

                        fos.close();

                    }

                } catch (IOException e) {

                    e.printStackTrace();

                    return ResultUtil.fail("UPLOAD_ERROR");

                }

            }

        }

        return ResultUtil.fail("UPLOAD_ERROR");

    }

     

     

     

}

请问用Java 如何实现图片上传功能 ?

我有一段上传图片的代码,并且可以根据实际,按月或按天等,生成存放图片的文件夹

首先在JSP上放一个FILE的标签这些我都不说了,你也一定明白,我直接把处理过程给你发过去

我把其中存到数据库中的内容删除了,你改一下就能用

/**

*

* 上传图片

* @param servlet

* @param request

* @param response

* @return

* @throws Exception

*/

//这里我是同步上传的,你随意

public synchronized String importPic(HttpServlet servlet, HttpServletRequest request,HttpServletResponse response) throws Exception {

SimpleDateFormat formatDate = new SimpleDateFormat("yyyyMM");

Date nowtime=new Date();

String formatnowtime=formatDate.format(nowtime);

File root = new File(request.getRealPath("/")+"uploadfile/images/"+formatnowtime+"/"); //应保证在根目录中有此目录的存在 如果没有,下面则上创建新的文件夹

if(!root.isDirectory())

{

System.out.println("创建新文件夹成功"+formatnowtime);

root.mkdir();

}

int returnflag = 0;

SmartUpload mySmartUpload =new SmartUpload();

int file_size_max=1024000;

String ext="";

String url="uploadfile/images/"+formatnowtime+"/";

// 只允许上载此类文件

try{

// 初始化

mySmartUpload.initialize(servlet.getServletConfig(),request,response);

mySmartUpload.setAllowedFilesList("jpg,gif,bmp,jpeg,png,JPG");

// 上载文件

mySmartUpload.upload();

} catch (Exception e){

response.sendRedirect()//返回页面

}

com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);

if (myFile.isMissing()){ //没有选择图片做提示!

returnflag = 3;

}else{

String myFileName=myFile.getFileName(); //取得上载的文件的文件名

ext= myFile.getFileExt(); //取得后缀名

if(ext.equals("jpg")||ext.equals("gif")||ext.equals("bmp")||ext.equals("jpeg")||ext.equals("png")||ext.equals("JPG")){ //jpeg,png不能上传!)

int file_size=myFile.getSize(); //取得文件的大小

String saveurl="";

if(file_sizefile_size_max){

try{

//我上面说到,把操作数据库的代友删除了,这里就应该是判断,你的图片是不是已经存在了,存在要怎么处理,不存在要怎么处了,就是你的事了 }

//更改文件名,取得当前上传时间的毫秒数值

Calendar calendar = Calendar.getInstance();

//String filename = String.valueOf(calendar.getTimeInMillis());

String did = contractBean.getMaxSeq("MULTIMEDIA_SEQ");

String filename = did;

String flag = "0";

String path = request.getRealPath("/")+url;

String ename = myFile.getFileExt();

//.toLowerCase()转换大小写

saveurl=request.getRealPath("/")+url;

saveurl+=filename+"."+ext; //保存路径

myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);

//将图片信息插入到数据库中

// ------上传完成,开始生成缩略图-----

java.io.File file = new java.io.File(saveurl); //读入刚才上传的文件

String newurl=request.getRealPath("/")+url+filename+"_min."+ext; //新的缩略图保存地址

Image src = javax.imageio.ImageIO.read(file); //构造Image对象

float tagsize=200;

int old_w=src.getWidth(null);

int old_h=src.getHeight(null);

int new_w=0;

int new_h=0;

int tempsize;

float tempdouble;

if(old_wold_h){

tempdouble=old_w/tagsize;

}else{

tempdouble=old_h/tagsize;

}

// new_w=Math.round(old_w/tempdouble);

// new_h=Math.round(old_h/tempdouble);//计算新图长宽

new_w=150;

new_h=110;//计算新图长宽

BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);

tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //绘制缩小后的图

FileOutputStream newimage=new FileOutputStream(newurl); //输出到文件流

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);

encoder.encode(tag); //近JPEG编码

newimage.close();

returnflag = 1;

}else{

returnflag = 0;

System.out.println("('上传文件大小不能超过"+(file_size_max/1000)+"K');");

}

}else{

returnflag = 2;

}

}

response.sendRedirect();

return "11";

}

关于java实现上传图片和java实现上传图片到APP端的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

发布于 2023-04-12 06:04:54
收藏
分享
海报
32
目录

    忘记密码?

    图形验证码

    复制成功
    微信号: cloud7591
    如需了解更多,欢迎添加客服微信咨询。
    我知道了